我有两个模型:书本和学生.我想要更新学生模型的书籍数组中特定书籍的一个字段.我如何首先查询学生,查询book数组中的一本书,然后更新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
}

如果我们想用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中使用.

Node.js相关问答推荐

无法从ejs Web应用程序中的正文中提取数据

模块';"; node :流程&没有导出的成员';dlopen';

一个函数中的两个依赖的NodeJS数据库操作.如果第二个失败了怎么办?

EJS ForEach循环标记

在对象的嵌套数组中使用$lookup,创建多个记录作为响应,mongodb

Express Web 服务器部署到 prod 但 GET 返回超时错误

在构建完成后,将AddedFiles文件夹的内容复制到dist文件夹

如何在 JavaScript 中显示多维数组中使用的一维数组的变量名?

MongoDB - 查找查询以判断是否存在少量字段,结合字段上的 AND

使用mongoose 创建新文档并仅取回选定的字段

Nodejs mongoose 在一个查询中从多个集合中获取结果

MongoDB Atlas中的聚合触发器不起作用

为什么当我try req.logout() 时出现此错误?

NodeJS 后端发布请求将数据作为NULL值发布到 SQL Server 表

GridFS 大文件下载使 Node.js 服务器崩溃. MongoServerError:排序超出了字节的内存限制

如何使用 Puppeteer 从输入中删除现有文本?

与 NPM 一起安装时找不到 Express 模块

通过 POST 请求将数据从 node.js 服务器发送到 node.js 服务器

如何让 Mocha 加载定义全局挂钩或实用程序的 helper.js 文件?

桌面应用程序仅支持 oauth_callback 值 'oob'/oauth/request_token