2017-02-14 68 views
0

我想推到sub-collectionMongoDB,我不知道該怎麼去做。不知道如何保存在MongoDB中

所以,我館藏結構:

{ 
    "_id": "58a3189b67476b420e465f8b", 
    "postID": "123456", 
    "comments": [ 
     { 
      "subComments": [], 
      "comment": "This is a test", 
      "commentID": 1 
     } 
    ] 
} 

所以,我想要做的就是使用findOneAndUpdate發現上面的文檔,然後選擇這個特殊的commentcommentID == 1),和然後推入它的subComments

我可以看你怎麼可以findOneAndUpdate通過它的postID並通過Mongoose推動加comments但我怎麼找到post,然後通過comment這是commentID,然後推入它的subComment

在此先感謝你們!非常卡住這個難題的最後一塊。

回答

1

與其他find查詢類似。

你可以試試這個:

Post.findOneAndUpdate({ 
    "postID" : givenPostID, 
    "comments.commentID" : givenCommentID 
},{ 
    $push : { 
     "comment.$.subComments" : givenSubComment 
    } 
},function(err,result){...}); 

comments.commentID: givenCommentID會發現comment元素與commentID == givenCommentID

comment.$.subCommentspushgivenSubCommentsubComments陣列comments陣列的matched元件的(匹配的基於commentID)。請致電MongoDB $(update) operator documentation

+0

如果像這樣的東西有效,生活會很好。然而,下面的行似乎不工作︰{$ push:{comments。$。subComments:req.body.comment}} - 我似乎無法找到任何關於這種「推」的文檔作爲我的問題似乎是一個語法錯誤。我的編輯已經告誡我了。任何想法交配?謝謝 –

+0

這適用於隊友,讓我用鏈接更新答案。另外,我已經編輯了一些答案,請嘗試一下,我相信它會起作用。原來我在更新查詢中錯過了''' –

+0

你還在面對這個問題嗎?或者它有效嗎? –

相關問題