2017-01-16 7 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 
     }); 
    }); 
}); 

を試してみましたが、されている。しかし、私はエラーを取得しています。どのように私はマングースを使って1つずつ投票を増やすのですか?

答えて

0

一緒$ 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更新演算子を使用し$ positional operatorは、あなたのケースでoptions配列のように埋め込まれた文書を含む配列への更新を容易にします。これにより、$ operatordot notationの埋め込みドキュメントのフィールドにアクセスできます。

+0

私はポールをヌルとして取得しています –

+0

これはおそらく、クエリが一致するドキュメントを見つけられなかったことを意味します。 'Poll.findOne({" _id ":req.params.id、" options._id ":req.body.id}、function(err、pol){console.log(pol);}というクエリでそれを確認できますか? }); '? – chridam

+0

これをnullにしています。しかし、同じidがmongodbに存在する –

関連する問題