【问题标题】:How to update nested mongo object如何更新嵌套的 mongo 对象
【发布时间】:2020-02-17 19:36:08
【问题描述】:

我正在尝试为我的应用制作报告功能

在前端我提出了一个 put 请求:

.put(`http://localhost:3000/api/posts/report`, {
                        params: {
                            id: mongoId,
                            reportInfo: {
                                reported: true,
                                reportingUser: id
                            }
                        }
                    })

到这个后端路由

router.put('/report', (req, res, next) => {
    postModel.findOneAndUpdate(
        { _id: mongoose.Types.ObjectId(req.query.id) },
        req.query,
        { new: true, useFindAndModify: false },
        (error, returnedDocuments) => {
            if (error) return next(error);
            res.json(returnedDocuments);
        }
    );
});

对于这个模型

const postSchema = new mongoose.Schema(
    {
        title: { type: String },
        description: { type: String },
        image: { type: String },
        price: { type: String },
        location: { type: String },
        image: { type: Array },
        author: {
            type: String,
            ref: 'User'
        },
        reportInfo: {
            reported:{
                type: Boolean,
                default: false
            },

            reportingUser:{
            type: String
            }

        }
    },
    {
        timestamps: true
    }
);

任何想法为什么它不更新 reportInfo 对象,如果包含一些嵌套对象,我需要做些什么吗?

谢谢

【问题讨论】:

    标签: javascript node.js reactjs mongodb express


    【解决方案1】:

    您的代码尝试替换整个 MongoDB 文档。尝试使用$set,而不是直接传递req.query

    { $set: { reportInfo: req.query.reportInfo } }
    

    我还会检查是否应该有 req.queryreq.body 所以只需打印该值以确保它被正确反序列化。

    【讨论】:

    • 是的,它的出现是未定义的...... req.query 是否仅适用于某些类型的请求?
    • 我使用查询来传递 axios 删除对象的数据,所以我不确定为什么它不适合 put req。
    • @jcx3x 通常它应该作为 HTTP 正文传递并且在 nodejs 中的 req.body 下可见
    猜你喜欢
    • 1970-01-01
    • 2019-02-20
    • 2021-01-23
    • 2016-08-26
    • 1970-01-01
    • 2022-12-21
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多