0

I need to create a compound query that retrieves all the document with a specific value in a map in an array. The useful part of my database looks like the following:

appointments(collection)
    doc1(document)
        people(array)
            person1(map)
                userId(field)
            person2(map)
                userId(field)

I need to get all the documents(like doc1) that have people with the specific userId, which is in a constant. I have a global idea of what needs to happen, but I don't really understand the query. I currently have the following:

const snapshot = db.collection('appointments').where('people.userId', 'array_contains', userId).get()
          .then(function(querySnapshot) {
              querySnapshot.forEach(function(doc) {
              db.collection('appointments').doc(doc.id).update({
                //Change the data I need to change
              },{merge:true});
           });
});

I cannot figure out how to construct this where clause. Can anyone help me with this? Thanks in advance!

1 Answer 1

2

It's not possible in Firestore to query for nested map values in an array. You will have to convert this data into something that can be queried, or duplicate enough of the data into another field to make it possible.

One thing you can do is create a new field that contains only the user ID strings, and use an array-contains query on that array.

Sign up to request clarification or add additional context in comments.

3 Comments

What would that look like then, because if I would have a separate array with the user ID's, I wouldn't know which data to update. Am I missing something here?
You would have to write code to update all the duplicate data if something changes. That's common for nosql type databases where data is duplicated.
So if I would create an array with all the userIDs in it, I could find all the documents I need to change something in, then loop trough the array and test if I have the correct data(by using change.before.data()), then change the data, that would work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.