Reputation: 3112
When updating a document in Firestore, I want to keep most of the document, but change one property which contains an object.
What I have
{
name: "John Doe",
email: "[email protected]",
friends: {
a: {...},
b: {...},
c: {...},
d: {...},
e: {...},
f: {...},
}
}
Now, I have a new friends object like {x: ..., y: ..., z: ...}
I want to overwrite the friends
tree of my document, but keep all other fields.
What I want it to look like
{
name: "John Doe",
email: "[email protected]",
friends: {
x: {...},
y: {...},
z: {...},
}
}
However, if I do a firestore.doc(...).update({friends: {...}}, { merge: true })
What I currently get
{
name: "John Doe",
email: "[email protected]",
friends: {
a: {...},
b: {...},
c: {...},
d: {...},
e: {...},
f: {...},
x: {...},
y: {...},
z: {...},
}
}
I know that I can do two updates, i.e. delete the field and then set it again, or I can read the document, change the object and save it without merging.
But isn't there a smart way to overwrite an object (map) while keeping the rest of the document untouched?
Upvotes: 5
Views: 5536
Reputation: 83153
Since you are using the update()
method, you just need to call it without a merge option.
firestore.doc(...).update({friends: {...}})
Note that update()
has two different signatures:
update(data: UpdateData)
and
update(field: string | FieldPath, value: any, ...moreFieldsAndValues: any[])
If the first argument you pass to the method is an object it will consider that you use the first signature and therefore you can pass only one argument. So doing
firestore.doc(...).update({friends: {...}}, { merge: true })
should generate the following error:
"Error: Function DocumentReference.update() requires 1 argument, but was called with 2 arguments."
On the other hand, you could call it this way:
firestore
.collection('...')
.doc('...')
.update(
'friends.c',
'Tom',
'email',
'[email protected]',
'lastUpdate',
firebase.firestore.FieldValue.serverTimestamp()
);
Finally, to be complete, note that if you do the following (passing one string)
firestore
.collection('...')
.doc('...')
.update(
'a_string'
);
you will get the following error
"Error: Function DocumentReference.update() requires at least 2 arguments, but was called with 1 argument."
which makes sense :-)
Upvotes: 6