2016-10-18 133 views
0

我很努力地更新mongoDB中嵌套的arrray內部的元素。嵌套數組mongoose內更新元素

可以說我有這樣的模式:

var question = new Schema({ 
    problem: { 
    type: String, 
    required: true 
    }, 
    multipleChoices: [{ 
    type: String, 
    required: true 
    }], 
    correctAnswer: { 
    type: Number, 
    required: true 
    } 
}); 

var testCategorySchema = new Schema({ 
    category: { 
    type: String, 
    required: true 
    }, 
    tests: [{ 
    version: { 
     type: String, 
     required: true 
    }, 
    questions: [question] 
    }] 
}); 

比如我有一個架構是這樣的實例:

{ 
    category: "Math", 
    tests: [ 
    { 
     version: "1A", 
     questions: [ 
     { 
      problem: "blablabla", 
      multiplechoices: [ 
      "bla bla", "blb blb", "blc blc" 
      ], 
      correctAnswer: 1 
     }, 
     { 
      problem: "blibliblibli", 
      multiplechoices: [ 
      "bla bla", "blb blb", "blc blc" 
      ] 
      correctAnswer: 1 
     } 
     ] 
    }, 
    { 
     version: "1B", 
     questions: [ 
     { 
      problem: "auauauauau", 
      multiplechoices: [ 
      "bla bla", "blb blb", "blc blc" 
      ] 
      correctAnswer: 1 
     }, 
     { 
      problem: "blibliblibli", 
      multiplechoices: [ 
      "bla bla", "blb blb", "blc blc" 
      ] 
      correctAnswer: 1 
     } 
     ] 
    } 
    ] 
} 

我如何添加新問題,以數學類時,測試版:1A使用mongooseJS?

回答

0

您需要使用​​和$push與位置操作$

db.test.update(
    { 
     category: 'Math', 
     'tests.version': '1A' 
    }, 
    { 
     $push: { 
      'tests.$.questions': { 
       problem: 'test', 
       multiplechoices: ['a', 'b', 'c'], 
       correctAnswer: 1 
      } 
     } 
    } 
+0

謝謝,我知道了。 但是我怎樣才能用貓鼬實現呢?我嘗試這樣做'TestCategory .findOne({category:req.params.TestCategory,tests:{$ elemMatch:{version:req.params.version}}})',那已經是正確的了嗎? – Kim

+0

只需使用'update'而不是'findOne'並相應地填充值......這裏不需要'$ elemMatch',這就是'$'的用途。 – TomG

+0

好吧,但是如果我只使用更新,我該如何顯示「未找到測試類別」? 對不起,還是有點迷惑呵呵 – Kim

0

試試這個..

Test.findOne({category:"Math", tests.version:"1A"}, function(err, result){ 
    if (!err && result) { 
    result.tests.questions.push({"new question"}); //push ur new question 
    var test = new Test(result); //this is ur mongoose mdel 
    test.save(function(err, result2){ //update 
     if(!err) { 
      console.log(result2); //updated result 
     } console.log(err); 
    }) 

    } else console.log(err); 
});