javascript – 使用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");

        }
  });

最佳答案 有一件事我想注意:medicalObj将是一个对象数组.我认为你想要将jobName:andrea添加到job中包含的特定数组中,所以这就是我在测试中所做的:

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