gpt4 book ai didi

javascript - 在 onwrite 事件中查询 firebase 数据库

转载 作者:行者123 更新时间:2023-12-01 02:32:22 25 4
gpt4 key购买 nike

我正在尝试编写一个 firebase 函数,它将检查“用户”并根据数据库写入事件进行行为。但是,当我查询数据库时,它每次都返回 null,而且我不知道我做错了什么。如有任何帮助,我们将不胜感激。

提前致谢。

我的实时数据库结构是这样的:

ilk-projemiz-cd55baddclose
users
edRIPg8BcZU9YPbubp7HtQo7phl1
sayilar: 1532
status: "on"
hakan
sayilar: 5000
status: "waiting"
mehmet
sayilar: 7000
status: "on"

我的 firebase 函数文件是这样的:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = event.data.adminRef.child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value", sorunsuz,sorunlu);
}
});

function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}

function sorunsuz(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}

最佳答案

这一行:const events = event.data.adminRef.child('users');尝试访问 users status下的节点节点。我认为您想要做的是访问根引用下的用户节点。

改用管理 SDK:

const events = admin.database().child('users');

更新:user变量超出范围,所以我建议您移动 sorunsuz()函数位于 on() 内功能:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = admin.database().child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value",
function(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}, sorunlu);
}
});

function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}

关于javascript - 在 onwrite 事件中查询 firebase 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48227675/

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