Reputation: 676
My functions should truncate a firestore collection and after populate it, the problem is that some documents are writtened after before all documents are deleted. I'm a noob with async await there is something wrong in my code :
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 !");
Upvotes: 0
Views: 69
Reputation: 7770
Couple of problems
You are not using Promise.all
for .map
so it is not really doing anything. Also you are not returning the promise from with in
THe populate method is using forEach which doesn't work with promises. Change that to use for..of
Something like this
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 !");
Upvotes: 1
Reputation: 350272
docs.map()
does not return a promise that resolves when all asynchronous deletions have been completed. Instead return
the promise returned by delete().then().catch()
and apply a Promise.all
on the return value of docs.map()
:
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);
});
}));
Upvotes: 0