简体   繁体   English

猫鼬 put 方法作为 post 方法工作

[英]mongoose put method is working as a post method

I created this web API using mongoose.我使用 mongoose 创建了这个 Web API。

POST and GET work fine, but mongoose seems to work like post, so instead of updating previous data, it creates a new one with a unique ID. POST 和 GET 工作正常,但 mongoose 似乎像 post 一样工作,因此它不会更新以前的数据,而是创建一个具有唯一 ID 的新数据。

Here is my code:这是我的代码:

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

Mongoose Schema猫鼬模式

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);

The formInput parameter to findByIdAndUpdate should be a plain object, not a Form instance: findByIdAndUpdateformInput参数应该是一个普通对象,而不是一个Form实例:

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

You don't need to create a new Form instance for updating, you can simply do你不需要创建一个新的 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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM