繁体   English   中英

如何在MongoDB / Node JS中的文档中查找和编辑数组元素的属性?

[英]How to find and edit the property of an array element inside a document in MongoDB/Node JS?

我有一个使用本机MongoDB驱动程序的MEAN堆栈应用程序。

Passport JS通过req.user.id提供登录用户的用户ID。 假设req.user.id =“ 10154053694878424”。

我不知道如何在数据库中找到属于用户的文档,如何在数组中查找元素以及如何更新该元素。 数据库中的文档如下所示:

{
  "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"}
  ] 
}

我有一条路线:

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的文档,如何在books数组中找到匹配的title元素,以及如何更改books数组的status属性? 我可以找到用户,返回文档,进行编辑,然后使用updateOne替换数据库中的文档。 但是可能必须有一种使用findAndModify的更有效的方法吗?

MongoDB位置

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM