无法在mongoose中更新嵌套模型

时间:2017-01-16 07:28:31

标签: node.js mongodb mongoose

我正在创建投票应用。我的架构定义如下

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
        });
    });
});

但是我收到了一个错误。如何使用mongoose增加一票?

1 个答案:

答案 0 :(得分:0)

$inc 更新运算符与$ 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
        }
    );
});

$ positional operator有助于更新包含嵌入式文档的数组,例如options数组。它允许您使用dot notation上的$ operator访问嵌入文档中的字段。