使用mongoose在mongo中更新第二级数组返回意外的令牌"。"

时间:2016-02-26 07:37:03

标签: node.js mongodb express mongoose

我有他的模特:

var field = {
    questionSets: [
        {
            name : "",
            questions: [
                {
                    question: {type: String, required: true},
                    answer: {type: String},
                }
            ]
        }
    ]
}

这个查询:

SubjectiveForm.update(
     {_id:doc._id, questionSets.$._id:req.params.set_id},
     {$pushAll: {questions:req.body}},
     {upsert:true},
     function(err, questions){
        console.log("err", err);
        console.log("err", questions);
     }
)

但这一行{_id:doc._id, questionSets.$._id:req.params.set_id},会在Unexpected token .上返回questionSets.$

BTW req.body看起来像这样(JSON):

[
    {
         "question" : "Added 1?"
    },
    {
         "question" : "Added 2?"
    }
]

1 个答案:

答案 0 :(得分:2)

由于questionSets.$._id是您提供给更新查询的JSON对象中的一个键,它应该是'questionSets.$._id'(带引号),它不能有一个包含点的键

SubjectiveForm.update(
     {_id:doc._id, 'questionSets.$._id':req.params.set_id},
     {$pushAll: {questions:req.body}},
     {upsert:true},
     function(err, questions){
        console.log("err", err);
        console.log("err", questions);
     }
)