Firestore: Query by item in array of document

2019-01-03 10:21发布

I have a document "user" which has a key called "photos". Here is an array of strings being saved, namely the IDs of the "photo" documents.

I want to query "user" by this "photos" field: I want all users who have this ID in the "photos" property.

Is this possible through firestore?

3条回答
趁早两清
2楼-- · 2019-01-03 10:51

Unfortunately not yet, although it's on our roadmap.

In the meantime, you'll need to use a map instead, in the form of:

photos: {
    id1: true
    id2: true
}

Now you can find all users with id1 by filtering by photos.id1 == true.

Read more about querying such sets in the Firebase documentation.

查看更多
倾城 Initia
3楼-- · 2019-01-03 10:51

Here is a bit of expansion on the answer as some seem to be confused about having to make indexes for each key, Firestore already indexes your data for simple queries thus you can do a simple query like

documentReference.where('param','==','value').onSnapshot(...)

but you can not do a compound query unless you index your data for those parameters. So you would need indexes to be able to do something like this:

 documentReference.where('param','==','value').where(..otherparams...).onSnapshot(...)

So as long as you need the photos for an id you can save them as

usersCollection :                        (a collection)
    uidA:                                (a document)
         photoField:                     (a field value that is a map or object)
            fieldID1 : true              (a property of the photoField)
            fieldID2 : true              (a property of the photoField)
            etc ...  

and you can simply query user(s) that have, let's say, fieldID1 in their photoField without needing to form any index and like query below.

firestore.doc('usersCollection/uidA').where('photoField.fieldID1','==',true).onSnapshot(...)
查看更多
Deceive 欺骗
4楼-- · 2019-01-03 11:05

Added 'array-contains' query operator for use with .where() to find documents where an array field contains a specific element.

https://firebase.google.com/support/release-notes/js 5.3.0

Update: also available in @google-cloud/firestore: https://github.com/googleapis/nodejs-firestore/releases/tag/v0.16.0

Update 2 https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

Update 3 now available in Admin Node.js SDK v6.0.0 https://github.com/firebase/firebase-admin-node/releases

查看更多
登录 后发表回答