2

This is my mongoose schema

var userSchema = new mongoose.Schema({
  referral:[{
    id:{type: String},
    name:{type: String}
  }],
  code:{type:String}
});

then I try to do something like this

User.findOneAndUpdate({code:'123'}, {$push:{'referral':{'id':'49385986','name':'myname'}}},
    function(err, result) {
        console.log(err);
        console.log(result);
    });

I can see the result, but when I check my db, it's not updated/inserted.

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Maria Jane
  • 2,353
  • 6
  • 23
  • 39

1 Answers1

0
Try This:

   User.findOneAndUpdate(
       {code:'123' },
       {
         $push: {
           referral: {
              $each: [ { id: "5", name:"abc" }, { id: "6", name: "xyz" }, { id: "7", name:"pqr" } ]
           }
         }
       },function(err,data){
        if(data){
         console.log(data); 
          }
        else{
        console.log(err);
         }

     });
    );
Shantanu Madane
  • 617
  • 5
  • 14
  • Kindly accept and upvote if it worked. $ each is used with the push whenever you want to insert one or many values into an array. – Shantanu Madane Sep 12 '16 at 12:03
  • Your code does not work because referal is an array,$each helps in adding elements at proper index but in your code it does not understand at what index the data must be added – Shantanu Madane Sep 12 '16 at 12:10