0
我有一個MEAN棧應用程序使用本地MongoDB驅動程序。如何在MongoDB/Node JS中的文檔中查找和編輯數組元素的屬性?
登錄用戶的用戶ID由Passport JS通過req.user.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數組的狀態屬性?我可以找到用戶,返回文檔,編輯該文檔,然後使用updateOne替換數據庫中的文檔。但是,使用findAndModify可能更有效嗎?