javascript - Firestore - 如何根据特定字段检查文档是否存在
问题描述
我想要实现的是根据 liker_id 之类的字段检查文档是否存在,如果存在则返回,如果不存在,则使用 liker_id 创建一个新文档。
我已经尝试了 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);
});
解决方案
你会试试这样的代码吗?
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);
});
推荐阅读
- css - CSS网格自动流如何工作?
- c - 使用clock_gettime() 的正确方法是什么?
- laravel - yajra Datatables 过滤并排序不在数据库中的数据
- java - 如何在 2d Arraylist 上使用 TrimToSize 方法?
- xslt - 使用 xls 删除属性值等于 0 的 xml 节点
- mysql - Mysql LEFT JOIN 结合 INNER 和 Group By
- java - 如何使用 javax.xml.bind 将 XML 写入带有 xmlns 字段的 POJO?
- r - split-lapply- 组合一个大数据帧以避免内存问题?
- android - 如何在我的联系人列表中搜索和拨打电话?
- r - 闪亮的仪表板 tabitem 没有显示