Estoy tratando de escribir una función de nube programada para restablecer el valor de "estado" todos los días a las 12 am. Aquí está mi estructura firestore:
Realmente no he intentado codificar en javascript antes, pero esto es lo que logré con mi poco conocimiento:
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; }); Recibo el siguiente error cuando implemento esta función:
Resultado esperado: establezca los valores de todos los campos de "estado" en 0.
Su alist devolverá una Promise { <pending> } . Debe cumplirse con un valor o rechazarse con un motivo (error). Debe usar el método .then para cumplir o usar el método .catch para obtener cualquier error de todas las promesas pendientes. Vea el código a continuación para referencia:
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); });Dejé algunos comentarios en el código para una mejor comprensión.
También puede consultar estas documentaciones:
Parece que alist es un objeto que Firestore no puede manejar. Para deshacerse de cualquiera de las partes que Firestore no puede manejar, puede hacer lo siguiente:
database.collection("SA1XAoC2A7RYRBeAueuBL92TJEk1") .doc("afternoon").update({ "list": JSON.parse(JSON.stringify(alist)) // 👈 });