简体   繁体   中英

How to update a Firestore field from a pub sub function

I have set up a pub/sub function to fire every minute and I want to check if the current time is equal to the start time any of the Firestore entities then change a value if it is :

exports.updateDraftStatus = (event, context) => {
  const pubsubMessage = event.data;
  console.log(Buffer.from(pubsubMessage, 'base64').toString());

  const db = admin.firestore();
  time = admin.firestore.Timestamp.fromMillis(Date.now())
  const snap = db.collection("leagues").where("startTime", time).get()
  await Promise.all(snap.docs.map(doc => doc.ref.update({Started: 'Off'})));
};

The .get() method returns a Promise<QuerySnapshot> , and not a QuerySnapshot . You will need to await the snapshot, or use a then() block.

exports.updateDraftStatus = async (event, context) => {
  const pubsubMessage = event.data;
  console.log(Buffer.from(pubsubMessage, 'base64').toString());

  const db = admin.firestore();
  time = admin.firestore.Timestamp.fromMillis(Date.now())
  const snap = await db.collection("leagues").where("startTime", time).get()
  await Promise.all(snap.docs.map(doc => doc.ref.update({Started: 'Off'})));
};

or

exports.updateDraftStatus = (event, context) => {
  const pubsubMessage = event.data;
  console.log(Buffer.from(pubsubMessage, 'base64').toString());

  const db = admin.firestore();
  time = admin.firestore.Timestamp.fromMillis(Date.now())
  return db.collection("leagues").where("startTime", time).get().then((snap) => {
    return Promise.all(snap.docs.map(doc => doc.ref.update({Started: 'Off'})));
  })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM