0

In the following snippet I am using mongoose and mongo db. The elements of arr property of TestSchema have different _id's after saving it the second time. Does that mean that the subdoc after the first save was automatically deleted after the second save ? or do I have to explicitly delete it before doing the second save ?

var SubSchema = new Schema({
    itemId : String, value : String
});

var TestSchema = new Schema({
    arr : [SubSchema],
    prop1 : String
})  ;

var TestModel = mongoose.model("TestModel",TestSchema);

var test1 = new TestModel();
test1.arr = [{itemId :'abcabcabcabc', value : 'value1'}];

 // first save
test1.save(function(err,testObj){
    if(err){
        console.error(err);
        return;
    }else{
        console.log("testObj : " + testObj ); 
        var id1 = testObj.arr[0].id;  // id of zeroth element after first save
        console.log("id1 : " + id1);

        // replace arr with a new array     
        testObj.arr = [{itemId:'1', value : 'val1'}, {itemId:'2', value:'val2'}];

        // second save
        testObj.save(function(err,testObj){
           if(err){
               console.error(err);
               return;
           }else{
               console.log("testObj : " + testObj);   // gives 2 elements in arr with new _id's
               var oldobj = testObj.arr.id(id1);
               console.log("oldobj : " + oldobj);   /// gives null
           }
        });
    }
});
Nitiraj
  • 614
  • 1
  • 4
  • 15
  • 1
    Your schema is embedded so there is no where else for them to be unless you are explicitly saving to another model. So if you replace one array with another then that is exactly what you get. – Neil Lunn Jun 18 '14 at 09:15
  • Thanks Neil. I was also thinking the same but I could not find it written anywhere. Thanks again. – Nitiraj Jun 18 '14 at 10:50

0 Answers0