我正在尝试为我的应用程序提供报告功能
在前端我发出放置请求:
.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对象,如果包含一些嵌套对象,我是否需要做些什么?
谢谢
答案 0 :(得分:0)
您的代码尝试替换整个MongoDB文档。尝试使用$set而不是直接传递req.query
:
{ $set: { reportInfo: req.query.reportInfo } }
我还将检查是否应该有req.query
或req.body
,因此只需打印值以确保正确反序列化即可。