I am trying to update a document for all findOneAndUpdate calls. So I wrote a post hook using the Mongoose Middleware. I am using Mongoose 4.6
mySchema.post('findOneAndUpdate', function(result) {
result.currentEvent = result.Events.slice(-1);
this.model.update({}, { currentEvent: result.currentEvent }).exec();
});
But this only updates the returned object, not the document in my collection. Is there a way to do this?
I am trying to update a document for all findOneAndUpdate calls. So I wrote a post hook using the Mongoose Middleware. I am using Mongoose 4.6
mySchema.post('findOneAndUpdate', function(result) {
result.currentEvent = result.Events.slice(-1);
this.model.update({}, { currentEvent: result.currentEvent }).exec();
});
But this only updates the returned object, not the document in my collection. Is there a way to do this?
Mongoose middleware documentation states:
Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated.
Try replacing your code with this:
mySchema.post('findOneAndUpdate', function(result) {
result.currentEvent = result.Events.slice(-1);
this.save(function(err) {
if(!err) {
console.log("Document Updated");
}
});
});
Hopefully, it should work.
You can also find the document and then save the modified document using this code:
mySchema.find({*condition*}, function(err, result) {
result.currentEvent = result.Events.slice(-1);
result.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
From mongoose 5.x
and in Node.js >= 7.6.0:
mySchema.post('findOneAndUpdate', async (result) => {
result.currentEvent = result.Events.slice(-1);
await result.save();
});
Instead of using POST Hook Use PRE Hook.
POST Hook: After the collection saved Post Hook will be executed. PRE Hook: Before saving the collection Pre Hook will be executed.
You can use the findOneAndUpdate hook and after you can use the method result.save()
mySchema.post('findOneAndUpdate', function(result) {
result.currentEvent = result.Events.slice(-1);
result.save(function(err) {
if(!err) {
console.log("Document Updated");
}
});
});