我正在尝试使用 where 从我的数据库中检索数据。用户输入他们想要邀请的电子邮件,然后发送邀请。但是,没有返回任何文件。这是我用来检索的代码:
await props.firestore
.collection("users")
.where("email", "==", state.inviteEmail)
.get()
.then((doc) => {
if (!doc.exists) {
props.showMsg(
"No user with that email exists. Make sure you've entered it correctly"
);
} else {
// This is where it goes if it works
alert("It works");
}
});
我试过用 .doc(any id) 替换 where 并且它可以工作,所以我知道数据库连接正确。这是数据库的视图:
我正在使用 Reactjs 而数据库正在使用 Firebase
编辑:对于其他有同样问题的人,这是我所做的改变:
await props.firestore
.collection("users")
.where("email", "==", state.inviteEmail)
.get()
.then((doc) => {
if (doc.empty) {
props.showMsg(
"No user with that email exists. Make sure you've entered it correctly"
);
} else {
alert("This emails username: "+doc.docs[0].data().username);
}
});
数据作为 QuerySnapshot 返回,它就像一个数组,所以它需要是 doc.docs[0].data 而不是 doc.Data()。因为我只有一个保证返回的文档,所以我只抓取了第一个元素,但是如果我有多个元素,我将不得不使用 foreach。
当您添加一个where
子句时,您实际上是在得到一个QuerySnapshot
对象而不是一个DocumentSnapshot
. 所以你的代码中的问题是QuerySnapshot
对象没有exists
作为DocumentSnapshot
对象的字段。因此在这种情况下doc.exists
将始终等于,undefined
并且 if 语句将始终评估为真。
您可以将 if 条件转换为查找empty
属性,因此代码将如下所示:
firestore
.collection("users")
.where("email", "==", state.inviteEmail)
.get()
.then((snap) => {
if (snap.empty) {
props.showMsg(
"No user with that email exists. Make sure you've entered it correctly"
);
} else {
// This is where it goes if it works
alert("It works");
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句