admin管理员组文章数量:1414628
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 badges4 Answers
Reset to default 2Mongoose 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");
}
});
});
本文标签: javascriptUpdate from mongoose post findOneAndUpdate hookStack Overflow
版权声明:本文标题:javascript - Update from mongoose post findOneAndUpdate hook - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745171843a2646022.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论