用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 Exercise = mongoose.model('Exercise',ExerciseSchema);

我想推入第二个嵌套数组中的新对象

我正在尝试这种方式,但不工作:

  Exercise.update({'area':area},{$push:{"medicalObj.job":{jobName:'Andrea'}}},{upsert:true},function(err){ if(err){ console.log("ERROR" + err); }else{ console.log("Successfully"); } }); 

       

网上收集的解决方案 "用Mongoose推入子数组"

有一件事我想注意:medicalObj将是一个对象的数组。 我想你会想将jobName:andrea添加到作业中包含的特定数组中,所以这就是我在testing中所做的:

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

如果您只希望插入jobName:“Andrea”(如果不存在),则可以轻松地添加一个符合以下内容的检查:

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