Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push in subarray with Mongoose

I've 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 the new object in the second nested array

I'm trying this way but is 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");

        }
  });
like image 335
jay Avatar asked Nov 02 '22 13:11

jay


1 Answers

One thing I'd like to note: medicalObj will be an array of Objects. I would think that you would want to add jobName: andrea to a specific array contained inside 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 wish to only insert jobName: "Andrea" if it don't exist, you can easily add a check along the lines of:

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);
        });
      };
    };
  });
});      
like image 58
thtsigma Avatar answered Nov 09 '22 16:11

thtsigma