update document firestore 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: document.set() firebasefirestore java

// Create an initial document to update.var frankDocRef = db.collection("users").doc("frank");frankDocRef.set({    name: "Frank",    favorites: { food: "Pizza", color: "Blue", subject: "recess" },    age: 12});// To update age and favorite color:db.collection("users").doc("frank").update({    "age": 13,    "favorites.color": "Red"});

Tags:

Java Example