Create and update data
We assume we already constructed a document reference, or perform a reference-less document creation.
document creation or override
We create or override document at docRef
setDoc(docRef, data)
docRef.set(data)
Reference-less document creation. By design a document won't exist there.
addDoc(collectionRef, data)
db.collection("message").add(data)
document partial update
If we assume the document already exists, we should use the update pattern, so that correctly fails if the document doesn't exist. Besides, TypeScript ensures we only update fields that are suppose to exist. The update pattern expects a change object, with one or more fields to update. The other fields are left unchanged. We type the change as a Partial of the document, or we explicitely pick fields with a Pick of the document.
updateDoc(docRef, data)
docRef.update(data)
upset and updating data
we can technically update a document with a modified upsert that comes with the option to merge what exists and what we provide. Yet, this is still dangerous because if we omit the merge option, the document will be overridden by the change object:
setDoc(docRef, data, { merge: true })
docRef.set(data, { merge: true })
delete document
docRef.delete()
deleteDoc(docRef)
mutate a single field
we use the update() function along with a directive on a specific field.
increment field
docRef.update({
count: FieldValue.increment(),
})
delete field
docRef.update({
fleet: FieldValue.delete(),
})
server timestamp for field
this creates a trusted timestamp object. this is not needed when doing it from admin-sdk, because we may already trust a date created from the admin environment. Besides, it uses firebase specific Timestamp instead of a multi platform iso date string.
docRef.update({
count: FieldValue.serverTimestamp(),
})
Increment
const partialUserDoc = {
activityScore: increment(1),
}