Click in a subarray using Mongoose

I have a datamodel with three levels of depth.

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

I want to push a new object in a second nested array

I am trying this, but not working:

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

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

        }
  });
+4
source share
1 answer

One thing I would like to point out: medicalObj will be an array of objects. I would think that you would want to add jobName: andrea to a specific array contained within the job, so this is what I did in my 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);
      });
  });
});

If you want to insert only name_name: β€œAndrea”, if it does not exist, you can easily add line-by-line checking:

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

All Articles