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.

9
  • 1
    @chridam where? please point it out Commented Sep 12, 2016 at 10:57
  • 2
    User.findOneAndUpdate({code:'123'},{}) Commented Sep 12, 2016 at 11:01
  • @ShantanuMadane I don't get it, can please post an answer? Commented Sep 12, 2016 at 11:03
  • @ShantanuMadane Tried to fix the typo, doesn't work too Commented Sep 12, 2016 at 11:04
  • 1
    if you don't see an error, and you get the result, your method is most likely successful, could you paste the log and result into the question Commented Sep 12, 2016 at 11:07

1 Answer 1

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

     });
    );
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.