更新文档数组中的文档Mongoose



我有两个模型:Book和Student。我想更新学生模型的图书数组中特定图书的字段。我如何首先查询学生,在books数组中查询一本书,然后更新book对象?

图书型号:


const bookSchema = new mongoose.Schema({
title:{
type: String
},
length:{
type:Number
},
author:{
type:String
},
ISBN:{
type:String
},
finished:{
type:Boolean
},
dueDate:{
type:String
},
imgURL:{
type:String
}
});
module.exports = mongoose.model("book", bookSchema);

学生模型:

const mongoose = require('mongoose');
const bookSchema = require('./book').schema;
const studentSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
books:{
type: [bookSchema]
}
});
module.exports = mongoose.model("student", studentSchema);```

您可以在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
}

如果我们想用这个_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);
});

在这里,我得到了params中的学生id,以及请求正文中的更新字段,您可以根据需要进行更改。

现在,如果我们发送一个带有此请求体的请求

{
"title": "book 2 title",
"finished": true
}

结果将是这样的:(标题为"图书2标题"的图书的完成属性更新为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
}

您可以在请求正文中发送更多字段,并在集合中使用。

最新更新