我需要一些帮助。
我试图对这条路线进行邮寄要求:
router.post('/admin/editFront', isLoggedIn, (req, res, next) => {
req.checkBody('title', 'Title is require').notEmpty();
req.checkBody('aboutUs', 'About us section is require').notEmpty();
req.checkBody('email', 'Check email again').notEmpty().isEmail();
let errors = req.validationErrors();
if(errors) {
req.flash('error_msg', errors.msg);
console.log(errors);
}
let cube = ({
title: req.body.cubeTitle,
img: req.body.cubeImg,
info: req.body.cubeInfo
})
let front = new FrontInfo();
front.title = req.body.title;
front.aboutUs = req.body.aboutUs;
front.email = req.body.email;
front.phone = req.body.phone;
front.cube.push(cube);
// front.socialNet.push(req.body.social);
console.log(front);
FrontInfo.findOneAndUpdate({email: req.body.email}, front, { upsert: true }, (err, doc) => {
if(err) console.log(err);
else {
req.flash('success', doc);
res.redirect('/editFront');
}
});
});
这是我的架构:
let cube = new Schema({
title: { type: String },
img: { type: String },
info: { type: String }
});
let socialNet = new Schema({
title: { type: String, required: true },
link: { type: String, required: true },
icon: { type: String, required: true }
});
let FrontInfo = new Schema({
title: { type: String, required: true },
aboutUs: {type: String, required: true},
phone: {type: String, minlength: 9, required: true},
email: {type: String, required: true},
cube: {type: [cube], default: []},
updateDate: {type: Date, default: Date.now}
});
所以,如果我尝试创建一个新的Schema,它就可以了。 但如果我尝试更新新的,我会收到此错误:
我花了很长时间试图修复它! 请帮帮我朋友
答案 0 :(得分:0)
当您使用let front = new FrontInfo();
时,您正在创建一个拥有自己的_id
的新文档。此_id
与您正在更新的文档的_id
不同。您不能更新_id
字段,这就是您收到错误消息的原因
(不可变)字段' _id'被发现被改为_id
因此,您应该只创建一个新的普通Javascript对象,而不是创建一个新的Mongoose文档:
let front = {};
front.title = req.body.title;
front.aboutUs = req.body.aboutUs;
front.email = req.body.email;
front.phone = req.body.phone;
front.cube = [];
front.cube.push(cube);
这仅包含您已列出的字段。