Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I've scoured SO a good bit looking for the answer but I'm sure that I'm lost for the right words to describe what I'm after.

Basically I have a mongodb collection called 'people' The schema for that collection is as follows:

people: { 

name: String, 

friends: [{firstName: String, lastName: String}] 

}

Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.

In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.

What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friend’s array.

I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

2 Answers

0 votes
by (106k points)

To push items into mongo array via mongoose assuming, 

var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend); 

person.save(done);

0 votes
by (107k points)

The $push operator adds a specified value to an array as its elements.

You can refer the following code:

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };

Friend.findOneAndUpdate(

   { _id: req.body.id }, 

   { $push: 

{ friend: objFriends  } },

  function (error, success) {

        if (error) {

            console.log(error);

        } else {

            console.log(success);

        }

    });

)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 5, 2020 in Web Technology by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...