MongoDB:如何查找和合并数组

时间:2016-08-01 14:54:58

标签: arrays node.js mongodb mongoose underscore.js

我正在尝试在我的文档中找到一个特定的ID,然后将一个数组合并到现有的数组中,例如,如果我将这个数组存储在db.friends中:

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

我发送这个数组:["12","16","18"],db.friends应该包含:["12","13","14","16","18"]

我正在使用下划线库,但我不确定是否必须(可能在mongoose中“聚合”?)

这是我做的,你能告诉我我错在哪里吗?

function saveFollowers(req, res) {
 var friends = req.body.friends; // the new array to 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 we have in db
        user.save(function (err) {
            if (err) { res.jsonp({error: "Cant save"}); }
            console.log("Friends NOW:"+JSON.stringify(friends)); //Here I don't see the merge, also, I can't see it in mongo db.
            res.jsonp("success");
        });
        }
    });

谢谢!

1 个答案:

答案 0 :(得分:0)

使用当前的实现,您实际上没有修改返回的用户对象中的friends键。因此,您可以使用 union 方法作为

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

或者使用ES6使用spread operator连接数组,使用Set创建一组不同的元素:

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

另一种方法是使用聚合框架,您可以使用 $setUnion 运算符:

function saveFollowers(req, res) {
    var friends = req.body.friends; // the new array to 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");
                }
            );
        }
    });
}
相关问题