I am working with a nestJS project and trying to return ids of inserted objects so they can later be used to populate the reference in a different object.
try {
await this.projectModel.insertMany(newProjects, (err, addedProjects) => {
const addedProjectsIds = addedProjects.map(ap => {
return ap._id;
});
ids = ids.concat(addedProjectsIds);
console.log('-------1--------');
console.log(ids);
});
} catch(err) {
isSuccessful = false;
errorMessage = err.message;
}
console.log('---------2--------');
console.log(ids);
return { success: isSuccessful, message: errorMessage, result: ids };
I would consistently receive an empty array added into reference ids and after some analysis identified the issue being in one block which seems to ignore the async/await syntax. In the following example, I am first getting ---2--- in the console and then ---1--- which means the ids are returned before they are populated by the insertMany callback.
Why is this happening despite using await on the mongoose method? How do I mitigate it?