gpt4 book ai didi

javascript - 如何使用 Firebase Cloud Functions 在 DataSnapshot 中查找特定值

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:49 25 4
gpt4 key购买 nike

我正在尝试制作一个云函数,它将在 HTTP 请求(通过计时器发送)上触发,这将删除所有具有特定值的 child 。

数据库节点如下所示:

activities
4GI1QXUJG0MeQ8Bq19WOdCQFo9r1 //uid
activity: "hammer"
id: some ID
note: "some note"
timestamp: some timeintervalsince1970
7IDUiufhiws8939hdfIUHiuhwdi5
etc....

我想查看所有的事件,如果事件值为“锤子”,我想移除这个 child 。

这是我目前的情况

exports.deleteHammerNotifications = functions.https.onRequest((req, res) => {

admin.database().ref('activities').once('value', (snapshot) => {

console.log(snapshot.val())

});
});

打印:

{ 
'4GI1QXUJG0MeQ8Bq19WOdCQFo9r1':
{ activity: 'nn',
id: '4GI1QXUJG0MeQ8Bq19WOdCQFo9r1',
note: 'Blank note...',
timestamp: 1498032472 },
M6xQU5XWTEVbSqBnR3HBAEhA9hI3:
{ activity: 'hammer',
id: 'M6xQU5XWTEVbSqBnR3HBAEhA9hI3',
note: 'some note here...',
timestamp: 1497973839 },
}

我的问题是我不知道如何循环浏览 DataSnapshot 并查找所有具有事件:“hammer”值的 child 。我在我的 xcode 项目中使用数组完成了类似的功能,但我不知道如何使用 JavaScript 完成它。

感谢任何帮助!

最佳答案

要循环遍历匹配的子节点,请使用 snapshot.forEach():

exports.deleteHammerNotifications = functions.https.onRequest((req, res) => {
admin.database().ref('activities').once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.val())
});
});
});

但是您在这里仍然缺少选择正确节点的查询。如果没有这样的查询,您还不如调用 admin.database().ref('activities').remove()

要最有效地从数据库中删除一些项目并将单个响应写回给用户,请使用此函数(我根据我最近需要的东西修改):

exports.cleanup = functions.https.onRequest((req, res) => {
var query = admin.database().ref("activities").orderByChild("activity").equalTo("hammer");
query.once("value").then((snapshot) => {
console.log("cleanup: "+snapshot.numChildren()+" activities");
var updates = {};
snapshot.forEach((child) => {
updates["activities/"+child.key] = null;
});
admin.database().ref().update(updates).then(() => {
res.status(200).send(snapshot.numChildren()+" activities deleted");
}).catch((error) => {
res.status(500).send(error);
})
});
});

了解更多:

关于javascript - 如何使用 Firebase Cloud Functions 在 DataSnapshot 中查找特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com