2016-08-01 2 views
1

내 문서에서 특정 ID를 찾은 다음이 배열을 db.friends에 저장 한 경우와 같이 기존 배열에 병합하려고합니다.MongoDB : 배열을 찾고 병합하는 방법은 무엇입니까?

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

내가이 배열 보내 ["12","16","18"]을 db.friends이 포함되어 있어야합니다 ["12","13","14","16","18"]

을 내가 밑줄 라이브러리를 사용하고 있습니다,하지만 난에이 확실하지 않다

을 (몽구스에 어쩌면 "집합"?)

내가 한 일은 내가 잘못 생각한 부분을 말해 줄 수 있습니까?

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

고마워요!

답변

0

현재 구현에서는 반환 된 사용자 객체에서 실제로 친구 키를 수정하지 않았습니다.

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

또 다른 대안은을 사용하고 있습니다 : 그래서 오히려 요소의 별개의 세트를 만들기위한 배열과 Set을 연결하기위한 spread operator를 사용 ES6

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

으로 또는 함께 union 방법을 사용할 수 있습니다 집계 프레임 워크를 사용하면 $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"); 
       } 
      ); 
     } 
    }); 
} 
+1

감사합니다. chridam, 내 하루를 보냈습니다! (나는 두 번째 함수를 사용했고, 그냥 작동한다.) .. :) – EranLevi

관련 문제