[英]Firestore - How to check if a document exist based on a specific field
What I want to achieve is to check if a document exist based on a field like liker_id and if it exist then return and if not then create a new document with the liker_id.我想要实现的是根据像liker_id这样的字段检查文档是否存在,如果存在则返回,如果不存在则使用liker_id创建一个新文档。
I've tried both snapshot.exists and doc.exists but they seem to give weird behaviors where the console.log doesn't get triggered or collection still adds document even though it already exists.我已经尝试过 snapshot.exists 和 doc.exists 但它们似乎给出了奇怪的行为,其中 console.log 没有被触发,或者集合仍然添加文档,即使它已经存在。
const liker = db
.collection("post")
.doc('ubxL0nDCLHgrtEyQ5TEV')
.collection("votes")
.where("liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3")
.get()
.then(snapshot => {
snapshot.forEach(doc => {
if (doc.exists) {
console.log("exist");
} else {
console.log("not exist");
}
});
})
.catch(error => {
console.log(error);
});
Would you try the code like this?你会尝试这样的代码吗?
const liker = db
.collection("post")
.doc('ubxL0nDCLHgrtEyQ5TEV')
.collection("votes")
.where("liker_id", "==", "user-TVe8mMRU47cnfO4xbl9yQEEE4XB3")
.get()
.then(snapshot => {
const data = snapshot.val();
data.forEach(doc => {
if (doc.exists) {
console.log("exist");
} else {
console.log("not exist");
}
});
})
.catch(error => {
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.