2017-01-16 1 views
3

투표 응용 프로그램을 생성 중입니다.중첩 된 모델을 몽구스로 업데이트 할 수 없습니다.

var option = new mongoose.Schema({ 
    title: {type: String, required: true}, 
    votes: { type: Number, default: 0 } 
}); 

var poll = new mongoose.Schema({ 
    question: { type: String, required: true, unique: true}, 
    options: { type: [option], required: true} 
}); 

아래 내가

app.put('/vote/:id', function(req, resp) { 
    Poll.findById(req.params.id , function(err, pol) { 
     pol.options.findById(req.body.id, function(err, option){// getting error in this line 
      //do my stuff 
     }); 
    }); 
}); 

을 시도하지만 오류가 점점 오전으로 내 스키마 정의입니다. 몽구스를 사용하여 투표 수를 늘리는 방법은 무엇입니까?

답변

0

따른 사용 $ positional operator 귀하의 경우에 options 배열과 같은 포함 된 문서를 포함하는 배열에 대한 업데이트를 용이하게 $ positional operator

app.put('/vote/:id', function(req, resp) { 
    Poll.findOneAndUpdate(
     { "_id": req.params.id, "options._id": req.body.id }, 
     { "$inc": { "options.$.votes": 1 } }, 
     { "new": true } 
     function(err, pol) { 
      // pol contains the modified document 
     } 
    ); 
}); 

로와 함께 $inc 업데이트 연산자. $ operatordot notation이 포함 된 포함 된 문서의 필드에 액세스 할 수 있습니다.

+0

폴을 null로 가져옵니다. –

+0

아마도 일치하는 문서를 찾지 못했음을 의미합니다. 'Poll.findOne ({ "_id": req.params.id, "options._id": req.body.id}, function (err, pol) {console.log (pol); });'? – chridam

+0

null로 처리합니다. 하지만 동일한 id가 mongodb에 존재합니다 –

관련 문제