2016-02-26 73 views
0

我使用这个查询:更新嵌套的数组不工作 - MongoDB的

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

路由呼叫:

localhost:3131/api/v0.1/charting/questions/56cff03e9ff240192da2fa34/set/56cff04e9ff240192da2fa3a/add-new-question 

其中:charting/questions/:questions_id/set/:set_id/add-new-question

文档数据:

/* 1 */ 
{ 
    "_id" : ObjectId("56cff03e9ff240192da2fa34"), 
    "questionSets" : [ 
     { 
      "name" : "Physical exam questions", 
      "_id" : ObjectId("56cff03e9ff240192da2fa35"), 
      "questions" : [ 
       { 
        "question" : "What is love?", 
        "answer" : "", 
        "_id" : ObjectId("56cff03e9ff240192da2fa39") 
       } 
      ] 
     }, 

     { 
      "name" : "Brain questions", 
      "_id" : ObjectId("56cff04e9ff240192da2fa3a"), 
      "questions" : [ 
       { 
        "question" : "What is love?", 
        "answer" : "", 
        "_id" : ObjectId("56cff04e9ff240192da2fa3e") 
       } 
      ] 
     } 
    ], 
    "updatedAt" : ISODate("2016-02-26T06:26:39.330Z") 
} 

我想推此JSON对象questionSets[0].questions

[ 

    { 
     "question" : "Added 1?" 
    } 
] 

但查询返回【OK:0,N:0,n修改:0}和文件尚未更新。我在这里做错了什么?谢谢。

回答

0

与数据

> db.questions.find().forEach(printjson) 
{ 
     "_id" : ObjectId("56d0143bd43e3500f6768488"), 
     "questionSets" : [ 
       { 
         "name" : "q1", 
         "_id" : "1", 
         "question" : [ 
           { 
             "question" : "here", 
             "answer" : "dd", 
             "_id" : "1" 
           } 
         ] 
       }, 
       { 
         "name" : "q2", 
         "_id" : "2", 
         "question" : [ 
           { 
             "question" : "you", 
             "answer" : "cc", 
             "_id" : "2" 
           } 
         ] 
       } 
     ] 
} 

运行命令

> db.questions.update({'questionSets._id': '1'}, 
         {$pushAll: { 
           'questionSets.$.question': [ 
                {question: 'you', 
                answer: 'are', 
                _id: '3'}]}}) 

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 
+0

嗨。它返回了这个错误。 '{名称: 'MongoError', 消息: '不能没有包含数组对应的查询字段申请的位置操作。', 司机:真, 确定:1, N:0, 代码:16650, ERRMSG :'不能应用位置运算符而没有包含数组的相应查询字段', writeConcernError: {code:16650, errmsg:'如果没有包含数组的相应查询字段,则无法应用位置运算符。 }} ' – CENT1PEDE

+0

@TheGreenFoxx,对不起以前的粗心大意,是'req.body'数组的值吗? – zangw

+0

是的,它看起来像这样。 '[{“question”:“Added 1?”}]' – CENT1PEDE