node.js - Push items into mongo array via mongoose -


i've scoured bit looking answer i'm sure i'm lost right words describe i'm after.

basically have mongodb collection called 'people' schema collection follows:

people: {          name: string,           friends: [{firstname: string, lastname: string}]         } 

now, have basic express application connects database , creates 'people' empty friends array.

in secondary place in application, form in place add friends. form takes in firstname , lastname , posts name field reference proper people object.

what i'm having hard time doing creating new friend object , "pushing" friends array.

i know when via mongo console use update function $push second argument after lookup criteria, can't seem find appropriate way mongoose this.

db.people.update({name: "john"}, {$push: {friends: {firstname: "harry", lastname: "potter"}}}); 

update: so, adrian's answer helpful. following did in order accomplish goal.

in app.js file, set temporary route using

app.get('/addfriend', users.addfriend); 

where in users.js file have

exports.addfriend = function (req, res, next) { var friend = {"firstname": req.body.fname, "lastname": req.body.lname}; users.findoneandupdate({name: req.user.name}, {$push: {friends: friend}}); }; 

assuming, var friend = { firstname: 'harry', lastname: 'potter' };

there 2 options have:

update model in-memory, , save (plain javascript array.push):

person.friends.push(friend); person.save(done); 

or

personmodel.update(     { _id: person._id },      { $push: { friends: friend } },     done ); 

i try , go first option when possible, because it'll respect more of benefits mongoose gives (hooks, validation, etc.).

however, if doing lots of concurrent writes, hit race conditions you'll end nasty version errors stop replacing entire model each time , losing previous friend added. go latter when it's absolutely necessary.


Comments

Popular posts from this blog

html - Difficulties with background-image property -

ios - Segue not passing data between ViewControllers -

ios - Change UITableView custom header view's button image not working -