我试图查询Firebase实时数据库,以检索特定用户的电子邮件,使用JavaScript。我想在查询中同时使用equalTo和orderByChild方法,但是遇到了一些问题。下面是我的代码片段:
const usersRef = ref(database, 'users');
const userEmail = "testemail123@gmail.com";
const query = query(usersRef, orderByChild('email'), equalTo(userEmail));
emailQuery.on('value', (snapshot) => {
if (snapshot.exists()) {
// The user with the email address `userEmail` was found.
const user = snapshot.val();
console.log(user)
} else {
// The user with the email address `userEmail` was not found.
}
});
字符串
但是,当我运行这段代码时,我得到一个错误,指出没有定义emailQuery.on。似乎我不能直接在查询函数中使用on()。
登录错误:emailQuery.on不是函数
如何定义“on()”?我如何修改我的代码以实现我想要的功能?
我已经尝试过其他函数,如once或forEach,但它们似乎提供了相同的错误。
我也试过这个代码:
const usersRef = ref(database, 'users');
console.log(usersRef);
usersRef.orderByChild('email').equalTo(userEmail)
.once('value').then((snapshot) => {
const userObject = snapshot.val();
console.log(userObject);
})
型
但它给了我一个错误:
登录错误:usersRef.orderByChild不是函数
1条答案
按热度按时间mbjcgjjk1#
您正在混合SDK版本/语法。
这一行使用SDK版本9中引入的模块化语法:
字符串
但在这一行中,你尝试使用一直存在的命名空间API调用:
型
虽然这两种语法都继续得到支持,但你不能随意使用混合和匹配。在一个文件中,您将不得不使用其中一个或另一个。
在模块化语法中相当于
ref.on(...)
,是全局onValue
函数,如Firebase文档中关于监听值事件的内容所示。基于此,您需要:
型