5

我有一个具有三个深度级别的数据模型。

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('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");

        }
  });
4

1 回答 1

2

我要注意的一件事:medicalObj 将是一个对象数组。我认为您可能希望将 jobName: andrea 添加到包含在作业中的特定数组中,所以这就是我在测试中所做的:

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);
        });
      };
    };
  });
});      
于 2013-10-11T17:31:37.683 回答