Reputation: 24405
I am trying to use the findOneAndUpdate
hook with Mongoose (discussed in detail here), although I'm having some problems trying to set a value post update.
For example:
MySchema.findOneAndUpdate({_id: fj394hri3hfj}, {$push: {comments: myNewComment}})
Will trigger the following hook:
MySchema.post('findOneAndUpdate', function(result) {
this.update({}, { totalNumberOfComments: result.comments.length });
});
Although, the hook will $push
to comments
the myNewComment
again, therefore making a duplicate entry.
I use this.update({}, {....})
instead of this.findOneAndUpdate({}, {....})
within the hook so that the post
hook is not called infinitely.
The totalNumberOfComments
is set perfectly to the length of comments.length
.
So it seems as if this.update({}, {....})
is just pushing more update fields to the already existing update fields on this
.
How can I just set totalNumberOfComments
within my hook instead of re-pushing to comments again?
Upvotes: 1
Views: 3583
Reputation: 3316
The issue seems to be in update query you wrote in post findOneAndUpdate
hook. Try replacing it with,
MySchema.post('findOneAndUpdate', function(result) {
this.totalNumberOfComments = this.result.comments.length;
this.save(function(err) {
if(!err) {
console.log("Document Updated");
}
});
});
And hopefully it should work.
I would also suggest, using find
and save
for updating document instead of findOneAndUpdate
and its post hook.
Edit:
In case you need to use find
and save
, you 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 it should work.
Upvotes: 5