2013-10-11 82 views
4

我有一個三層深度的數據模型。推入Mongoose的子陣列

var job = mongoose.Schema({ 
     id:Number, 
     jobName:String  
    }); 

var demo = mongoose.Schema({ 

      id:Number, 
      demoName:String, 
      job:[job] 
    }); 

var ExerciseSchema = mongoose.Schema({ 

      id:Number, 
      name:String, 
      area:String, 
      medicalObj:[demo] 
    }); 

VAR練習= mongoose.model( '運動',ExerciseSchema);

我要推新對象的第二嵌套數組

我想這樣,但不工作:

Exercise.update({'area':area},{$push:{"medicalObj.job":{jobName:'Andrea'}}},{upsert:true},function(err){ 

     if(err){ 
       console.log("ERROR" + err); 
     }else{ 
       console.log("Successfully"); 

     } 
    }); 
+0

'{'area':area}'或'{area:'area'}'?你有什麼錯誤? –

+0

相同的函數在數組的第二級工作。 但我沒有錯誤,但只是不工作。運動.update({'area':area},{$ push:{medicalObj:{a:'Andrea'}}},{upsert:true},函數(err){err} {err} {err} {err} { console.log(「ERROR」+ err); } else { console.log(「Successfully added」); } }); – jay

回答

2

有一件事我想指出:medicalObj將是一個對象數組。我會認爲你想工作名補充:安德烈包含內部作業的特定陣列,所以這是我在我的測試做:如果「安德烈」:

Exercise.findOne({area: area}, function(e,r){ 
    r.medicalObj.forEach(function(demo){ 
    // the following line looks for the specific array to add jobName Andrea to. 
    if (demo.demoName == "test") { 
     demo.job.push({jobName: "Andrea"}); 
     r.save(function(err, res){ 
     console.log(err, res); 
     }); 
    }); 
}); 

如果你希望只插入作業名不存在,你可以很容易地添加一個檢查線:

Exercise.findOne({area: area}, function(e,r){ 
    r.medicalObj.forEach(function(demo){ 
    if (demo.demoName == "test") { 
     var found = false; 
     demo.job.forEach(function(jobs){ 
     if (jobs.jobName == "Andrea") found == true; 
     }); 
     if (found == false) { 
     demo.job.push({jobName: "Andrea"}); 
     r.save(function(err, res){ 
      console.log(err, res); 
     }); 
     }; 
    }; 
    }); 
});