猫鼬put方法正在用作发布方法

问题描述 投票:0回答:2

我使用猫鼬创建了此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);
javascript node.js mongodb mongoose
2个回答
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);
  });
});

0
投票

formInputfindByIdAndUpdate参数应该是普通对象,而不是Form实例:

const formInput = {
    firstname: req.body.firstname,
    lastname: req.body.lastname,
};

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);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.