0

Suppouse a firestore Database filled with this structure, being Events and Users collections:

Firestore
    -Events
        -1612483200
            -peopleSignedDict
                -Alex
                    -state: 1
                -Mark:
                    -state: 0
        -1606172400
            -peopleSignedDict                
    -Users
        -1zyXSMMlGiaUusUNLQWAxfsI4pM2
            -name: Alex
        -4zyXSMMlGiaUusUNLQWAxfsI4pM2
            -name: Mark

I'm using Node.js and trying to update Events.1612483200.peopleSignedDict.Alex.state to change the state from 1 to 0. To achieve it I'm trying to do:

var randomName = getRandomDBName();
db.collection('Events').doc('1612483200').set({
            'peopleSignedDict.'+randomName+'.state': 0
        });

But ofc my IDE (PhpStorm) yells at me telling that this syntax is not valid, which should be the correct syntax to approach this?

1 Answer 1

2

There's a few way to do this.

My favorite is to first construct the key in a separate variable, and then use that in the collection:

let randomName = getRandomDBName();
let updates = {};
updates['peopleSignedDict.'+randomName+'.state'] = 0;
db.collection('Events').doc('1612483200').update(updates);

But a common (and shorter) alternative is:

let randomName = getRandomDBName();
db.collection('Events').doc('1612483200').update({ 
  [`peopleSignedDict.${randomName}.state`]: 0;
});

I'm actually not sure if the [] are needed in that last snippet, so if you have problems with it, try it without them and let me know.

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

2 Comments

Thanks @Frank, you're the firebase-man to me! I've tested and without the [ ] won't work, it also works with [ ] and + instead of using $. But one question before accepting the answer, this currently creates a field called peopleSignedDict.Name.state instead of updating the value inside the Map, is the espected behaviour? Feels like this should be done using "update", instead of "set" maybe? Thanks again! ^^
Good catch. This should indeed have been an update call. I fixed it in my answer.

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.