2016-06-09 4 views
0

here에 대해 findOneAndUpdate 후크를 사용하려고합니다. 업데이트 후 값을 설정하는 데 문제가 있습니다. 예를 들어'findOneAndUpdate`로 포스트 업데이트로 값 설정하기 몽구스 후크

: 후크 $push 다시 myNewCommentcomments에 따라서 중복 항목을 만드는 것입니다,하지만

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을 내 후크 안에 다시 설정할 수 있습니까?

+0

'findOneAndUpdate' 후크가 귀하의 케이스에서 불려지고 있습니까? – Raeesaa

+0

글쎄, 내 'findOneAndUpdate' 호출과 다시 한번 hook 내부에서 호출되기 때문에 중복을 생성하는 이유입니다. 나는 또한 내부에서'console.log (this)'를했는데 성공적으로 기록되었다. 문제는'this는 여전히'$ push : {comments : myNewComment} '업데이트를 유지하고 있으며,'$ set' 업데이트를 두 번 푸시하여'$ push'를 두 번 수행한다는 것입니다. – Fizzix

+0

확인. 포스트 후크를 꼭 사용해야합니까? 대신에'find'와'save'를 대신 할 수 있습니다. – Raeesaa

답변

4

문제는 findOneAndUpdate 후크에 작성한 업데이트 쿼리에있는 것 같습니다. 이를 (를) 대체 해보십시오.

MySchema.post('findOneAndUpdate', function(result) { 
    this.totalNumberOfComments = this.result.comments.length; 
    this.save(function(err) { 
     if(!err) { 
      console.log("Document Updated"); 
     } 
    }); 
}); 

잘하면 작동해야합니다.

findOneAndUpdate 및 포스트 후크 대신 문서를 업데이트하는 데 findsave을 사용하는 것이 좋습니다.


편집 : 당신이 findsave를 사용해야 할 경우

는, 당신이 위의 코드를 대체 할 수

MySchema.findById(fj394hri3hfj, function(err, doc){ 

    doc.comments.push(myNewComment); 
    doc.totalNumberOfComments += 1; 
    doc.save(function(err){ 

     console.log("Document Updated");  
    }); 
}); 

하고 작동합니다.

+1

저장 중에 주석 길이를 설정하는 두 번째 옵션을 선택하기로 결정했습니다. 아마도 그렇게하는 것이 더 좋을 것입니다. 나는 미래에 주석 삭제도 허용하려고합니다. 12 시간 만에 현상금을 수여합니다. 감사! – Fizzix

+0

이런 식으로'.save()'를 사용할 때는 조심성이 보장되지 않는다. –

관련 문제