您可以在findOneAndUpdate方法中使用$set运算符.
假设您有一份包含两本书的学生文档:
{
"_id": "6314eda827c01a07746bceff",
"name": "student 1",
"books": [
{
"_id": "6314eda827c01a07746bcf00",
"title": "book 1 title",
"length": 1,
"author": "book 1 author",
"ISBN": "book 1 ISBN",
"finished": true,
"dueDate": "book 1 dueDate",
"imgURL": "book 1 imgURL"
},
{
"_id": "6314eda827c01a07746bcf01",
"title": "book 2 title",
"length": 2,
"author": "book 2 author",
"ISBN": "book 2 ISBN",
"finished": false,
"dueDate": "book 2 dueDate",
"imgURL": "book 2 imgURL"
}
],
"__v": 0
}
如果我们想用this_id和其中一个书名更新学生,我们可以这样做:
app.put('/students/:studentId', async (request, response) => {
const { studentId } = request.params;
const { title, finished } = request.body;
const result = await Student.findOneAndUpdate(
{
_id: new mongoose.Types.ObjectId(studentId),
'books.title': title,
},
{
$set: {
'books.$.finished': finished,
},
},
{
new: true,
}
);
response.send(result);
});
在这里,我在参数中获得了学生ID,在请求正文中获得了UPDATE字段,您可以根据需要进行更改.
现在,如果我们发送包含此请求正文的请求
{
"title": "book 2 title",
"finished": true
}
结果如下所示:(书名为‘book 2 title’的图书的Finish属性更新为True.
{
"_id": "6314eda827c01a07746bceff",
"name": "student 1",
"books": [
{
"_id": "6314eda827c01a07746bcf00",
"title": "book 1 title",
"length": 1,
"author": "book 1 author",
"ISBN": "book 1 ISBN",
"finished": true,
"dueDate": "book 1 dueDate",
"imgURL": "book 1 imgURL"
},
{
"_id": "6314eda827c01a07746bcf01",
"title": "book 2 title",
"length": 2,
"author": "book 2 author",
"ISBN": "book 2 ISBN",
"finished": true,
"dueDate": "book 2 dueDate",
"imgURL": "book 2 imgURL"
}
],
"__v": 0
}
您可以在请求Body中发送更多字段,并在Set中使用.