2016-11-11 8 views
0

私は、ネイティブのMongoDBドライバを使ってMEANスタックアプリを持っています。MongoDB/Node JSの文書内の配列要素のプロパティを見つけて編集する方法は?

ログインしたユーザーのユーザーIDは、req.user.idを介してPassport JSによって提供されます。 req.user.id = "10154053694878424"としましょう。

ユーザーに属するデータベースで文書を検索し、配列内の要素を見つけてその要素を更新する方法を理解できません。私は、ユーザーIDと、データベース内の文書を見つけることができ、書籍の配列に一致するタイトル要素を見つける方法

app.post("/changestatus", function(req,res){ 

    //req.body is an object with title of the book 
    //for example: {"title": "Harry Potter"} 

    //find user with req.user.id 
    //check requests array and see which element matches "title":"Harry Potter" 
    //change "status" to "accepted" instead of "pending" 

) 

:私はルートを持っている

{ 
    "id": "10154053694878424", 
    "name: "John Doe", 
    "city: "Amsterdam", 
    "books": [{},{},{}], 
    "requests": [ 
    {"title": "Harry Potter", "author": "JK Rowling", "status": "pending"}, 
    {"title": "Lord of the Rings", "author": "JR Tolkien", "status": "pending"} 
    ] 
} 

:データベース内の文書は、次のようになりbooks配列のstatusプロパティを変更しますか?ユーザーを見つけてドキュメントを返し、編集してから、データベースのドキュメントを置き換えるためにupdateOneを使用することができました。しかし、おそらくfindAndModifyを使ってより効率的な方法が必要でしょうか?

答えて

1

MongoDB Positional

// find data where id == req.user.id and requests.title = harry potter 
db.collection 
.update({ 
    id: req.user.id, 
    "requests.title": "Harry Potter" 
}, { 
    $set: { 
     "requests.$.status": "accepted" 
    } 
}); 
関連する問題