node.js - catch error thrown in a mongoose callback
You need to deal with the fact that the callback will fire long before an error would be thrown, as it's in a callback of it's own. I would suggest Promise.all to wait on all save operations, which return promises.
function generateInvitations(requirements) { const { expirationDate, credits, numOfUse, numOfInvites } = requirements; let promises = []; for (let i = 0; i < numOfInvites; i++) { const code = randomString(CODE_LENGTH); const invitation = new Invitation({ // code, numOfUse, expirationDate, credits }); promises.push(invitation.save()); } return Promise.all(promises):}
And then:
generateInvitations(requirements) .then(data => res.status(200).json({data})) .catch(err => { console.log(`caught the error: ${err}`); return res.status(500).json(err); });