猫鼬put方法正在作为post方法

时间:2020-01-17 02:47:19

标签: javascript node.js mongodb mongoose

我使用猫鼬创建了这个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);

2 个答案:

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