node.js - MongoDB: how can I find and merge array -


i'm trying find specific id in document , merge array existing one, example if have array stored in db.friends:

["12","13","14"] 

and send array: ["12","16","18"], db.friends should contain: ["12","13","14","16","18"]

i'm using underscore library, i'm not sure have (maybe "aggregate" in mongoose?)

here did, can tell me wrong?

function savefollowers(req, res) {  var friends = req.body.friends; // new array merge ["54aafe9df4ee360300fc94c7"];   user.findone({_id: req.user._id}).exec(function (err, user) {       if (err) {           res.jsonp({error: "error fetching user info"})       } else {         friends = _.extend(friends, user.friends); //user.friends=existing friends have in db         user.save(function (err) {             if (err) { res.jsonp({error: "cant save"}); }             console.log("friends now:"+json.stringify(friends)); //here don't see merge, also, can't see in mongo db.             res.jsonp("success");         });         }     }); 

thank you!

with current implementation, haven't modified friends key in returned user object. rather can use union method as

user.friends = _.union(friends, user.friends); //user.friends=existing friends          user.save(function (err) { .. } 

or es6 using spread operator concatenating array , set creating distinct set of elements:

user.friends = [...new set([...friends ,...user.friends])]; user.save(function (err) { .. } 

another alternative using aggregation framework, utilize $setunion operator:

function savefollowers(req, res) {     var friends = req.body.friends; // new array merge ["54aafe9df4ee360300fc94c7"];      user.aggregate([         { "$match": { _id: req.user._id } },         {              "$project": {                 "friends": { "$setunion": [ "$friends", friends ] }                          }         }     ]).exec(function (err, results){         if (err) {             res.jsonp({error: "error fetching user info"})         } else {             user.findbyidandupdate(req.user._id,                  { "$set": { "friends": results[0].friends } },                  { "new": true },                 function (err, user) {                     if (err) { res.jsonp({error: "cant save"}); }                     console.log("friends now: "+ json.stringify(user.friends));                      res.jsonp("success");                 }             );         }     }); } 

Comments