【发布时间】:2019-03-29 13:23:24
【问题描述】:
我想知道是否有办法检查 Cloud Firestore 文档中是否存在属性。 document.contains("property_name") 之类的东西,或者是否存在文档属性。
【问题讨论】:
标签: node.js firebase google-cloud-firestore
我想知道是否有办法检查 Cloud Firestore 文档中是否存在属性。 document.contains("property_name") 之类的东西,或者是否存在文档属性。
【问题讨论】:
标签: node.js firebase google-cloud-firestore
要解决这个问题,您可以像这样简单地检查 DocumentSnapshot 对象的无效性:
var yourRef = db.collection('yourCollection').doc('yourDocument');
var getDoc = yourRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
if(doc.get('yourPropertyName') != null) {
console.log('Document data:', doc.data());
} else {
console.log('yourPropertyName does not exist!');
}
}
})
.catch(err => {
console.log('Error getting document', err);
});
【讨论】:
你可以像下面的 sn-p 一样使用in 运算符
const ref = admin.firestore().collection('yourCollectionName').doc('yourDocName')
try {
const res = await ref.get()
const data = res.data()
if (!res.exists) {
if (!("yourPropertyName" in data)) {
// Do your thing
}
} else {
// Do your other thing
}
} catch (err) {
res.send({err: 'Something went terribly wrong'})
}
【讨论】:
我认为您指的是进行查询。 仍然无法检查 Firestore 中是否存在某些字段。但是您可以添加另一个值为 true/false
的字段val query = refUsersCollection
.whereEqualTo("hasLocation", true)
query.get().addOnSuccessListener {
// use the result
}
查看此链接了解更多信息
https://firebase.google.com/docs/firestore/query-data/queries How do I get documents where a specific field exists/does not exists in Firebase Cloud Firestore?
【讨论】: