Reputation: 28328
I have this model/schema:
const InviteSchema = new Schema({
inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true},
organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Organisation', required: true},
sentTo: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true},
createdAt: {type: Date, default: new Date(), required: true}
});
InviteSchema.post('save', function(err, doc, next) {
// This callback doesn't run
});
const Invite = mongoose.model('Invite', InviteSchema);
module.exports = Invite;
Helper function:
exports.sendInvites = (accountIds, invite, callback) => {
let resolvedRequests = 0;
accountIds.forEach((id, i, arr) => {
invite.sentTo = id;
const newInvite = new Invite(invite);
newInvite.save((err, res) => {
resolvedRequests++;
if (err) {
callback(err);
return;
}
if (resolvedRequests === arr.length) {
callback(err);
}
});
});
};
And the router endpoint which calls the helper function:
router.put('/organisations/:id', auth.verifyToken, (req, res, next) => {
const organisation = Object.assign({}, req.body, {
updatedBy: req.decoded._doc._id,
updatedAt: new Date()
});
Organisation.findOneAndUpdate({_id: req.params.id}, organisation, {new: true}, (err, organisation) => {
if (err) {
return next(err);
}
invites.sendInvites(req.body.invites, {
inviter: req.decoded._doc._id,
organisation: organisation._id
}, (err) => {
if (err) {
return next(err);
}
res.json({
error: null,
data: organisation
});
});
});
});
The problem here is that the .post('save')
hook doesn't run, despite following the instructions, i.e. using .save()
on the model instead of .findOneAndUpdate
for example. I've been digging for a while now but I cannot see what the problem here could be.
The Invite
document(s) are saved to the database just fine so the hook should fire, but doesn't. Any ideas what could be wrong?
Upvotes: 4
Views: 7131
Reputation: 3111
You can declare the post hook with different number of parameters. With 3 parameters you are treating errors, so your post hook will be called only when an error is raised. But, if your hook has only 1 or 2 parameters, it is going to be executed on success. First parameter will be the document saved in the collection, and second one, if passed, is the next element. For more information, check official doc: http://mongoosejs.com/docs/middleware.html Hope it helps.
Upvotes: 11