[英]How to check if a cloud firestore document exists when using realtime updates
This works:这有效:
db.collection('users').doc('id').get()
.then((docSnapshot) => {
if (docSnapshot.exists) {
db.collection('users').doc('id')
.onSnapshot((doc) => {
// do stuff with the data
});
}
});
... but it seems verbose. ......但似乎很冗长。 I tried doc.exists
, but that didn't work.我试过doc.exists
,但这没有用。 I just want to check if the document exists, before subscribing to realtime updates on it.我只想在订阅文档的实时更新之前检查文档是否存在。 That initial get seems like a wasted call to the db.最初的 get 似乎是对数据库的浪费调用。
Is there a better way?有没有更好的办法?
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
}
});
Reference: Get a document参考: 获取文档
In case you are using PHP-Firestore integration, like me, write something like this:如果您像我一样使用 PHP-Firestore 集成,请编写如下内容:
$firestore = new FirestoreClient();
$document = $firestore->document('users/john');
$snapshot = $document->snapshot();
if ($snapshot->exists()) {
echo "John is there!";
}
Enjoy!享受! o/ o/
Please check following code.请检查以下代码。 It may help you.它可能会帮助你。
const userDocRef = await firestore().collection('collection_name').doc('doc_id');
const doc = await userDocRef.get();
if (!doc.exists) {
console.log('No such document exista!');
} else {
console.log('Document data:', doc.data());
}
I know its late, but it's actually snapshot.empty not snapshot.exists .我知道它迟到了,但它实际上是 snapshot.empty 而不是 snapshot.exists 。 snapshot.empty checks if a doc exists and returns accordingly. snapshot.empty 检查文档是否存在并相应返回。 happy coding 😊快乐编码😊
请注意,在火力地堡V9(模块化SDK) exists
是一种方法,而不是一个属性(它会给你falsy
结果所有的时间),按照该文档。
If you are using Angular you can use the AngularFire package to check it with an observable. 如果您使用的是Angular,则可以使用AngularFire包以可观察的方式对其进行检查。
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
constructor(private db: AngularFirestore) {
const ref: AngularFirestoreDocument<any> = db.doc(`users/id`);
ref.get().subscribe(snap => {
if (snap.exists) {
// ...
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.