firestore update document code example
Example 1: 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();
//Successful operation
response.send("200");
});
Example 2: firestore set a document
let data = {
name: 'Los Angeles',
state: 'CA',
country: 'USA'
};
// Add a new document in collection "cities" with ID 'LA'
let setDoc = db.collection('cities').doc('LA').set(data);
Example 3: firestore update array
let washingtonRef = db.collection('cities').doc('DC');
// Atomically add a new region to the "regions" array field.
let arrUnion = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
let arrRm = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});
Example 4: firestore update map
let initialData = {
name: 'Frank',
age: 12,
favorites: {
food: 'Pizza',
color: 'Blue',
subject: 'recess'
}
};
let updateNested = db.collection('users').doc('Frank').update({
age: 13,
'favorites.color': 'Red'
});
Example 5: firebase cloud method update
firebase deploy --only functions:functionNameHere
Example 6: document.set() firebasefirestore java
var washingtonRef = db.collection("cities").doc("DC");// Atomically add a new region to the "regions" array field.washingtonRef.update({ regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")});// Atomically remove a region from the "regions" array field.washingtonRef.update({ regions: firebase.firestore.FieldValue.arrayRemove("east_coast")});