Update nested objects
If your document contains nested objects, you can use "dot notation" to reference nested fields within the document when you call update():
import { doc, setDoc, updateDoc } from "firebase/firestore";
// Create an initial document to update.
const frankDocRef = doc(db, "users", "frank");
await setDoc(frankDocRef, {
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
});
// To update age and favorite color:
await updateDoc(frankDocRef, {
"age": 13,
"favorites.color": "Red"
});
// To update food without the dot notation.
// NOTICE favorits.color vs food:"Ice Cream"
db.collection("users").doc("frank").update({
favorites: {
food: "Ice Cream"
}
}).then(function() {
console.log("Frank food updated");
});
const initialData = {
name: 'Frank',
age: 12,
favorites: {
food: 'Pizza',
color: 'Blue',
subject: 'recess'
}
};
// ...
const res = await db.collection('users').doc('Frank').update({
age: 13,
'favorites.color': 'Red'
});