Maria Jane Maria Jane - 2 months ago 8
Node.js Question

Mongoose $push doesn't insert arrays

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 update/inserted.

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

     });
    );