[英]How to find and edit the property of an array element inside a document in MongoDB/Node JS?
I have a MEAN stack app using the native MongoDB driver. 我有一个使用本机MongoDB驱动程序的MEAN堆栈应用程序。
The user id of the logged in user is provided by Passport JS via req.user.id. Passport JS通过req.user.id提供登录用户的用户ID。 Let's say req.user.id = "10154053694878424".
假设req.user.id =“ 10154053694878424”。
I can't figure out how to find a document in the database belonging to the user, find an element in an array, and update that element. 我不知道如何在数据库中找到属于用户的文档,如何在数组中查找元素以及如何更新该元素。 The documents in the database look like this:
数据库中的文档如下所示:
{
"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"}
]
}
I have a route: 我有一条路线:
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"
)
How can I find the document in the database with the user ID, find the matching title element in books array and change the status property of the books array? 如何在数据库中找到具有用户ID的文档,如何在books数组中找到匹配的title元素,以及如何更改books数组的status属性? I could find the User, return the document, edit that and then use updateOne to replace the document in the database.
我可以找到用户,返回文档,进行编辑,然后使用updateOne替换数据库中的文档。 But there must be a more efficient way using findAndModify maybe?
但是可能必须有一种使用findAndModify的更有效的方法吗?
// 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.