简体   繁体   English

如何更新嵌套的 mongo 对象

[英]How to update nested mongo object

I am trying to make a report function for my app我正在尝试为我的应用程序制作报告功能

in the front end I make a put request :在前端,我提出一个放置请求:

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

to this backend route到这个后端路由

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);
        }
    );
});

for this model对于这个模型

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
    }
);

any ideas why it is not updating the reportInfo object , do I need to do something if there are some nested objects contained?任何想法为什么不更新 reportInfo 对象,如果包含一些嵌套对象,我是否需要做一些事情?

thanks谢谢

Your code tries to replace entires MongoDB document.您的代码尝试替换整个 MongoDB 文档。 Try to use $set instead of passing req.query directly:尝试使用$set而不是直接传递req.query

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

I would also check if there should be req.query or req.body so just print the value to make sure that it gets deserialized properly.我还会检查是否应该有req.queryreq.body所以只需打印该值以确保它被正确反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM