我的函数应该截断一个firestore集合,并在填充它之后,问题是某些文档是在删除所有文档之后写入的。我是异步等待的菜鸟,我的代码有问题:

let db = admin.firestore();

let truncateCollection = async function () {
    const snapshot = await db.collection(collectionToPopulate).get();
    await snapshot.docs.map(function (doc) {
        db.collection(collectionToPopulate).doc(doc.id).delete().then(function () {
            console.log("document supprimé : "+doc.id);
        }).catch(function (error) {
            console.error("erreur de suppression de document",error);
        });
    });
    await populate();
};

let populate = async function () {
    jsonInput.forEach(function (obj, index) {
        Object.entries(obj).forEach(([key,value]) => {
            //console.log(value);
            db.collection(collectionToPopulate).doc(key).set({
                name: value.name,
                imageUrl: value.image_url,
            }).then(function (docRef) {
                console.log("Document written with ID: ", key);
            }).catch(function (error) {
                console.error("Error adding document: ", error);
            });
        });
    });
};

truncateCollection();
res.send("Job Done !");

最佳答案

几个问题


您没有将Promise.all用于.map,所以它实际上没有做任何事情。您也不会从in中退还诺言
填充方法使用的是forEach,它与诺言不兼容。更改为使用for..of


像这样

const db = admin.firestore();

// eslint-disable-next-line func-style
const truncateCollection = async function () {
  const snapshot = await db.collection(collectionToPopulate).get();
  await Promise.all(snapshot.docs.map(function (doc) {
    return db.collection(collectionToPopulate).doc(doc.id).delete().then(function () {
      console.log(`document supprimé : ${doc.id}`);
    }).catch(function (error) {
      console.error("erreur de suppression de document", error);
    });
  }));
  await populate();
};

// eslint-disable-next-line func-style
const populate = async function () {
  for (const obj of jsonInput) {
    for (const [key, value] of Object.entries(obj)) {

      try {
        // eslint-disable-next-line no-await-in-loop
        const response = await db.collection(collectionToPopulate).doc(key).set({
          "name": value.name,
          "imageUrl": value.image_url
        });
        console.log("Document written with ID: ", key);
      } catch(err) {
        console.error("Error adding document: ", error);

      }
    }
  }
};

truncateCollection();
res.send("Job Done !");

07-24 09:50
查看更多