Mongodb findOneAndUpdate无法正常工作

时间:2018-07-04 04:14:20

标签: mongodb

我正在尝试更新mongodb集合中的文档,但它对我不起作用。这是所有字段都传到后端的功能。我在网上使用mlab mongo db

router.post(
  '/accept',
  (req,res) => {
    const leaveFields = {};
    leaveFields._id = req.body.id;
    leaveFields.name = req.body.name;
    leaveFields.reason = req.body.reason;
    leaveFields.from = req.body.from;
    leaveFields.to = req.body.to;
    leaveFields.user_id = req.body.user_id;
    leaveFields.leaveType = req.body.leaveType;
    console.log(req.body.id);
    Leave.find({user_id:req.body.user_id})  //{ "_id":ObjectId("req.body.id") }
      .then(leave =>{
        if(leave){
          Leave.findOneAndUpdate(
            {_id : req.body.id},
            {$set : leaveFields},
            {new : true}
        )}else{
          res.status(400).json(errors);
        }
      }
        )
      .catch(err=>res.status(404).json({ noleavefound: 'No leaves found' }));

1 个答案:

答案 0 :(得分:0)

在这里,您将_id设置为leftfields对象,并且

const leaveFields = {};
leaveFields._id = req.body.id;

在这里,您还将_id字段也传递给您的更新。

{$set : leaveFields}

_id字段是不可变的字段。因此,请排除_id字段,然后进行检查。