如何在使用实时更新时检查是否存在云防火墙文档 [英] How to check if a cloud firestore document exists when using realtime updates
本文介绍了如何在使用实时更新时检查是否存在云防火墙文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这有效:
db.collection('users').doc('id').get()
.then((docSnapshot) => {
if (docSnapshot.exists) {
db.collection('users').doc('id')
.onSnapshot((doc) => {
// do stuff with the data
});
}
});
......但似乎很冗长。我试过doc.exists,但那没用。我只想在订阅文档上的实时更新之前检查文档是否存在。那个初始的get似乎是对db的一个腰部调用。
... but it seems verbose. I tried doc.exists, but that didn't work. I just want to check if the document exists, before subscribing to realtime updates on it. That initial get seems like a waisted call to the db.
还有更好的方法吗?
推荐答案
您的初始方法是正确的,但将文档引用分配给变量可能不那么冗长:
Your initial approach is right, but it may be less verbose to assign the document reference to a variable like so:
const usersRef = db.collection('users').doc('id')
usersRef.get()
.then((docSnapshot) => {
if (docSnapshot.exists) {
usersRef.onSnapshot((doc) => {
// do stuff with the data
});
} else {
usersRef.set({...}) // create the document
}
});
参考:获取文档
这篇关于如何在使用实时更新时检查是否存在云防火墙文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文