我使用猫鼬创建了此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);
您无需创建新的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);
});
});
formInput
的findByIdAndUpdate
参数应该是普通对象,而不是Form
实例:
const formInput = {
firstname: req.body.firstname,
lastname: req.body.lastname,
};
您不需要创建新的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);
});
});