簡體   English   中英

調度雲 function 更新地圖列表

[英]Schedule cloud function to update a list of maps

我正在嘗試編寫一個預定的雲 function 以每天凌晨 12 點重置“狀態”的值。 這是我的 Firestore 結構:Firestore 數據

我以前沒有真正嘗試過在 javascript 中編碼,但這是我用我的一點知識管理的:

const functions = require("firebase-functions");

const admin = require("firebase-admin");
admin.initializeApp();

const database = admin.firestore();


exports.Rst = functions.pubsub.schedule("0 0 * * *").onRun((context) => {
  const alist =
      database.collection("SA1XAoC2A7RYRBeAueuBL92TJEk1")
          .doc("afternoon").get().then((snapshot)=>snapshot.data["list"]);

  for (let i=0; i<alist.length; i++) {
    alist[i]["status"]=0;
  }

  database.collection("SA1XAoC2A7RYRBeAueuBL92TJEk1")
      .doc("afternoon").update({
        "list": alist,
      });

  return null;
});

部署此 function 時出現以下錯誤:錯誤

預期結果:將所有“狀態”字段的值設置為 0。預期結果

您的列表將返回alist Promise { <pending> } 它需要用一個值來實現或用一個原因(錯誤)拒絕。 您應該使用.then方法來實現或使用.catch方法來獲取所有未決承諾的任何錯誤。 請參閱下面的代碼以供參考:

const collectionName = "SA1XAoC2A7RYRBeAueuBL92TJEk1";
const documentName = "afternoon";
// created a reference to call between functions
const docRef = database.collection(collectionName).doc(documentName);

// Initialized a new array that will be filled later.
const tasks = [];

// Gets the data from the document reference
docRef.get()
// Fulfills the promise from the `.get` method
.then((doc) => {
  // doc.data.list contains the array of your objects. Looping it to construct a `tasks` array.
  doc.data().list.forEach((task) => {
    // Setting the status to 0 for every object on your list
    task.status = 0;
    // Push it to the initialized array to use it on your update function.
    tasks.push(task);
  })

  docRef.update({
    // The `tasks` structure here must be the same as your Firestore to avoid overwritten contents. This should be done as you're updating a nested field.
    list: tasks
  }, { merge: true });
})
// Rejects the promise if it returns an error.
.catch((error) => {
  console.log("Error getting document:", error);
});

為了更好地理解,我在代碼上留下了一些評論。


您可能還想查看這些文檔:

看來alist是Firestore無法處理的object。 要擺脫 Firestore 無法處理的任何部分,您可以執行以下操作:

database.collection("SA1XAoC2A7RYRBeAueuBL92TJEk1")
    .doc("afternoon").update({
      "list": JSON.parse(JSON.stringify(alist)) // 👈
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM