firestore update document field code example
Example 1: Firestore increment field
const userRef = db.collection('documents').doc('document_id');
const increment = firebase.firestore.FieldValue.increment(1);
userRef.update({ FieldToIncrease: increment });
Example 2: firestore cloud function update documents
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
export const setProductsToExpired = functions.https.onRequest(async(request, response) => {
const expiredProducts = await admin.firestore()
.collection('products')
.where('timestamp','<=', admin.firestore.Timestamp.now())
.get();
const batch = admin.firestore().batch();
expiredProducts.forEach(doc => {
batch.update(doc.ref,'expired',true);
});
await batch.commit();
response.send("200");
});
Example 3: firestore set a document
let data = {
name: 'Los Angeles',
state: 'CA',
country: 'USA'
};
let setDoc = db.collection('cities').doc('LA').set(data);
Example 4: firestore create document with auto id
db.collection("cities").add({
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
---------------------------
db.collection("cities").doc("TYO").set({
name: "Tokyo",
country: "Japan"
})
Example 5: firestore update array
let washingtonRef = db.collection('cities').doc('DC');
let arrUnion = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
let arrRm = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});
Example 6: firebase cloud method update
firebase deploy --only functions:functionNameHere