mongodb - Setting a value post update with the `findOneAndUpdate` Mongoose hook -
i trying use findoneandupdate hook mongoose (discussed in detail here), although i'm having problems trying set value post update.
for example:
myschema.findoneandupdate({_id: fj394hri3hfj}, {$push: {comments: mynewcomment}}) will trigger following hook:
myschema.post('findoneandupdate', function(result) { this.update({}, { totalnumberofcomments: result.comments.length }); }); although, hook $push comments mynewcomment again, therefore making duplicate entry.
i use this.update({}, {....}) instead of this.findoneandupdate({}, {....}) within hook post hook not called infinitely.
the totalnumberofcomments set length of comments.length.
so seems if this.update({}, {....}) pushing more update fields existing update fields on this.
how can set totalnumberofcomments within hook instead of re-pushing comments again?
the issue seems in update query wrote in post findoneandupdate hook. try replacing with,
myschema.post('findoneandupdate', function(result) { this.totalnumberofcomments = this.result.comments.length; this.save(function(err) { if(!err) { console.log("document updated"); } }); }); and should work.
i suggest, using find , save updating document instead of findoneandupdate , post hook.
edit:
in case need use find , save, can replace above code with:
myschema.findbyid(fj394hri3hfj, function(err, doc){ doc.comments.push(mynewcomment); doc.totalnumberofcomments += 1; doc.save(function(err){ console.log("document updated"); }); }); and should work.
Comments
Post a Comment