问题描述
我有一个关于firebase中的firestore数据库的问题.
I have a question regarding the firestore db from firebase.
我有一个文档X,其中包含一个名为users的字段,该字段是一个引用users集合内用户的对象.
I have a document X that contains a field called users that is an object with references to users inside the users collection.
看起来与此类似:
families: [{
xyz: {
name:'foobar',
users: {
john: 'users/john', //reference to another document
mike: 'users/mike' //reference to another document
}
}
},
...]
如何查询firestore数据库以获取具有用户名称"john"的所有文档(来自familys集合)?
How can I query the firestore db to get all documents (from the families collection) that have a user with the name 'john'?
我没有运气就尝试了以下方法:
I tried the following without luck:
db.collection('families')
.where('users.john', '<', '')
但是它只返回一个空数组.
But it only returns an empty array.
如果我将用户条目从key:reference切换到key:string对象,它将起作用.但是我想使用Refreences,而不是字符串.
If I switch the users entry from key:reference to key:string object it works. But I want to work with refrences and not strings.
推荐答案
Firestore无法提供查询字段是否存在的方法.它用于查找文档的索引基于属性的 values .现在,您的值是文档参考,因此您只能查询它们的参考值.
Firestore doesn't provide a way to query for the simple existence of fields. The indexes it uses to find documents are based on the values of a property. Right now, your values are document references, so you can only query against their reference values.
如果您想知道文档中是否存在某些内容,则可以为其创建一个带有布尔值的新字段.然后,您可以查询是非.
If you want to know if a something exists in a document, you could create a new field for it with a boolean value. You can then query that for true or false.
families: [{
xyz: {
name:'foobar',
users: {
john: 'users/john', //reference to another document
mike: 'users/mike' //reference to another document
},
users_exists: {
john: true,
mike: true
}
}
},
有了上面的users_exists,现在您可以像这样查询:
With users_exists in place above, now you can query like this:
db.collection('families')
.where('users_exists.john', '==', true)
NoSQL数据建模的一般规则是以适合您要执行的查询的任何方式进行.有时,这涉及复制数据以适合那些查询.
The general rule for NoSQL data modeling is to do it in whatever way suits the queries you intend to perform. Sometimes this involves duplicating data to suit those queries.
这篇关于查询firebase firestore db,其中collection具有带引用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!