javascript - Update from mongoose post findOneAndUpdate hook - Stack Overflow

admin2025-04-21  0

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?

Share Improve this question asked Dec 20, 2016 at 21:56 jdeyrupjdeyrup 1,1441 gold badge13 silver badges13 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

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");
        }
     });
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745171845a288704.html

最新回复(0)