here에 대해 findOneAndUpdate
후크를 사용하려고합니다. 업데이트 후 값을 설정하는 데 문제가 있습니다. 예를 들어'findOneAndUpdate`로 포스트 업데이트로 값 설정하기 몽구스 후크
: 후크 $push
다시 myNewComment
comments
에 따라서 중복 항목을 만드는 것입니다,하지만
MySchema.post('findOneAndUpdate', function(result) {
this.update({}, { totalNumberOfComments: result.comments.length });
});
:
MySchema.findOneAndUpdate({_id: fj394hri3hfj}, {$push: {comments: myNewComment}})
은 다음과 훅을 트리거합니다.
this.findOneAndUpdate({}, {....})
대신 을 사용하여 post
후크를 무제한 호출하지 않습니다.
totalNumberOfComments
은 길이가 comments.length
으로 완벽하게 설정됩니다.
마치 this.update({}, {....})
이 이미 업데이트 필드에 더 많은 업데이트 필드를 넣는 것 같습니다 (this
).
코멘트로 다시 푸는 대신 totalNumberOfComments
을 내 후크 안에 다시 설정할 수 있습니까?
'findOneAndUpdate' 후크가 귀하의 케이스에서 불려지고 있습니까? – Raeesaa
글쎄, 내 'findOneAndUpdate' 호출과 다시 한번 hook 내부에서 호출되기 때문에 중복을 생성하는 이유입니다. 나는 또한 내부에서'console.log (this)'를했는데 성공적으로 기록되었다. 문제는'this는 여전히'$ push : {comments : myNewComment} '업데이트를 유지하고 있으며,'$ set' 업데이트를 두 번 푸시하여'$ push'를 두 번 수행한다는 것입니다. – Fizzix
확인. 포스트 후크를 꼭 사용해야합니까? 대신에'find'와'save'를 대신 할 수 있습니다. – Raeesaa