我使用猫鼬创建了这个Web API。
POST和GET可以很好地工作,但是猫鼬的工作原理类似于post,因此它不会更新以前的数据,而是创建一个具有唯一ID的新数据。
这是我的代码:
router.put("/update", (req, res, next) => {
const formInput = new Form({
// _id: '5e20275e2d0f182dd4ba320a',
firstname: req.body.firstname,
lastname: req.body.lastname,
});
Form.findByIdAndUpdate({_id: '5e20275e2d0f182dd4ba320a'}, formInput, {new: true}, (err, result) => {
if (err) return res.status(500).send(err);
return res.send(result);
});
});
猫鼬模式
var formSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
firstname: {
type: String,
// required: true
},
lastname: {
type: String,
// required: true
},
},
{
collection: 'formsInput'
});
module.exports = mongoose.model('Form', formSchema);
答案 0 :(得分:0)
formInput
的{{1}}参数应该是普通对象,而不是findByIdAndUpdate
实例:
Form
答案 1 :(得分:0)
您无需创建新的Form实例进行更新,只需执行
router.put("/update", (req, res, next) => {
Form.findByIdAndUpdate({_id: '5e20275e2d0f182dd4ba320a'}, {...req.body}, {new: true}, (err, result) => {
if (err) return res.status(500).send(err);
return res.send(result);
});
});