Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Firestore: Update fields in nested objects with dynamic key

following the official documentation of firestore :

{
    name: "Frank",
    favorites: { food: "Pizza", color: "Blue", subject: "recess" },
    age: 12
}

// To update favorite color:
db.collection("users").doc("frank").update({
    "favorites.color": "Red"
})

I would like to use a dynamic key instead of color.

db.collection("users").doc("frank").update({
    "favorites[" + KEY + "].color": true
});

this is of course not possible and will throw an error.

I've been trying to do this :

db.collection("users").doc("frank").update({
    favorites: {
        [key]: {
            color": true
        }
    }
});

It is actually updating with the right key but unfortunately, it is overwriting the other keys (they are being deleted).

like image 500
Brieuc Avatar asked Nov 14 '17 21:11

Brieuc


People also ask

Can firestore update multiple documents matching a condition using one query?

Cloud Firestore does not support the equivalent of SQL's update queries.


3 Answers

I found the solution inspired by a firebase solution (replacing "/" by ".").

var usersUpdate = {};
usersUpdate[`favorites.${key}.color`] = true;

db.collection("users").doc("frank").update(usersUpdate);
like image 65
Brieuc Avatar answered Oct 17 '22 22:10

Brieuc


This solution worked for me:

db.collection('users').doc('frank').update({
  [`favorites.${key}.color`]: true
});
like image 37
Georg Hackenberg Avatar answered Oct 17 '22 23:10

Georg Hackenberg


Just a note about a potential pitfall: After discovering that you can update nested fields using a dot syntax, I tried using set() the same way, since I needed it to work whether the object already exists or not:

var updateObj = {['some.nested.property']: 9000};
docRef.set(updateOb, {merge: true});

Unfortunately, this doesn't work – it sets a property whose key is some.nested.property instead. Inconsistent, but okay.

Fortunately, it appears that set(updateObj, {merge: true}) does a deep merge, so if you construct your update object as a fully nested object, your nested objects will also be properly merged:

// create the object
db.doc('testCollection/doc').set({p1: {['p2']: {p3: true}}}, {merge: true})
// update the existing object
db.doc('testCollection/doc').set({p1: {['p2']: {p4: true}}}, {merge: true})

// result is now this:
{ p1: { p2: { p4: true, p3: true } } }
like image 28
undefined Avatar answered Oct 17 '22 23:10

undefined