簡體   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