2017-11-19 12 views
0

게시물 컬렉션을 업데이트하고 각 코멘트를 업데이트하고 싶습니다. 어떻게해야합니까?MongoDB 객체의 배열 내부에서 쿼리와 일치하는 객체 업데이트

{ 
    "pid": "kennethlumalicay-ja55nh40ja64br0h", 
    ...more_stuff, 
    "comments": [ 
     { 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Full Stack", 
      "comment": "hey" 
     }, 
     { 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Full Stack", 
      "comment": "what" 
     }, 
     { 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Full Stack", 
      "comment": "now" 
     } 
    ] 
}, ...other_posts 

이 내 코드입니다 :

은 샘플입니다

Post.updateMany({ 'comments.uid': user.uid } 
    , { 'comments.$': { 
     username: user.username, 
     usertag: user.usertag 
    }} 
    , null 
    ,() => { 
     fetchPosts(null, (posts) => { 
     cb({ 
      posts: posts, 
      user: user 
     }); 
     }); 
    }); 

내가 무엇을 기대 : uid가와 의견이있는 각 게시물을 찾아 각 주석을 업데이트합니다.

{ 
    "pid": "kennethlumalicay-ja55nh40ja64br0h", 
    ...more_stuff, 
    "comments": [ 
     { 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Front End", // updated 
      "comment": "hey" 
     }, 
     { 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Front End", // updated 
      "comment": "what" 
     }, 
     { 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Front End", // updated 
      "comment": "now" 
     } 
    ] 
}, ...other_posts 

대신에 어떻게됩니까 : uid가와 의견이있는 각 게시물을 찾아 하나의 주석을 업데이트 및 기타 속성을 제거합니다.

{ 
    "pid": "kennethlumalicay-ja55nh40ja64br0h", 
    ...more_stuff, 
    "comments": [ 
     { // removed uid and comment 
      "username": "kennethlumalicay", 
      "usertag": "Front End" 
     }, 
     { // nothing 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Full Stack", 
      "comment": "what" 
     }, 
     { // nothing 
      "uid": "kennethlumalicay-ja55nh40", 
      "username": "kennethlumalicay", 
      "usertag": "Full Stack", 
      "comment": "now" 
     } 
    ] 
}, ...other_posts 

달성이 가능합니까 아니면 다른 의견 모음을 만들어서 게시 ID를 저장해야합니까? 또는 코멘트를 렌더링 할 때마다 uid에 사용자 데이터베이스를 가져와야하나요? 하지만 그건 좋지 않습니다.

답변

0

"coments. $"에 "$"연산자를 사용하고 있습니다. 워드 프로세서 밖으로

확인 : https://docs.mongodb.com/manual/reference/operator/update/

$ 업데이 트에 쿼리 조건에 일치하는 첫 번째 요소를 업데이트하는 자리 표시 자 역할을합니다.

또한, 그래서 u는 단지 이름usertag 필드를 포함하는 새로운 개체와 전체 "코멘트"OBJ을 무시하지 r에, 당신은 $ 세트 연산자를 사용하고 싶은 생각합니다.

시도 :

Post.updateMany({ 'comments.uid': user.uid } 
    , { 'comments': $set: { 
     username: user.username, 
     usertag: user.usertag 
    }} 
    , null 
    ,() => { 
     fetchPosts(null, (posts) => { 
     cb({ 
      posts: posts, 
      user: user 
     }); 
     }); 
    });