简体   繁体   中英

Update from mongoose post findOneAndUpdate hook

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:

Edited to correct typo:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM