0

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?

qubits
  • 1,227
  • 3
  • 20
  • 50
  • You can only `await` a promise, and `insertMany` is taking a callback – Quentin Jan 09 '20 at 10:20
  • 1
    @Quentin I'm not sure if the linked question is correct since `insertMany` already returns a Promise so there's nothing to promisify. It seems the issue was a bit different. Correct me if I'm wrong – Sebastian Kaczmarek Jan 09 '20 at 10:26

1 Answers1

1

await will not work if you rely on the callback. As far as I know, insertMany returns a Promise - and that's what await can work with. Try with something like this:

const addedProjects = await this.projectModel.insertMany(newProjects);
const addedProjectsIds = addedProjects.map(ap => {
    return ap._id;
});
ids = ids.concat(addedProjectsIds);
console.log('-------1--------');
console.log(ids);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • Thanks, looks this was it. I would assume the callback should also be awaited. All works now. – qubits Jan 09 '20 at 10:25