【问题标题】:Update a record where _id = :id with Mongoose使用 Mongoose 更新 _id = :id 的记录
【发布时间】:2013-06-19 11:38:57
【问题描述】:

我正在尝试使用 Mongoose 更新现有记录。插入正常,但没有更新。

这是我的sn-p:

app.post('/submit', function(req, res) {

    var my_visit = new models.visits({
        date: req.body.visit_date,
        type: req.body.visit_type,
        agency: req.body.visit_agency,
        city: req.body.visit_city,
        url: req.body.visit_url,
        note: req.body.visit_note
    });

    // INSERT
    if(req.body.id == 0) {
        my_visit.save(function(err) {
            if(err) { throw err; }

            console.log('added visit');

            res.redirect('/');
        });
    } else { // UPDATE
        var upsertData = my_visit.toObject();

        console.log(req.body.id); // OK

        models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) {
            if(err) { throw err; }

            console.log('updated visit: '+ req.body.id);

            res.redirect('/');
        });
    }


})

回复是Mod on _id is not allowed

我只想更新 MySQL 中的WHERE id = id 等行。我没有找到正确的语法。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    根据this questionthis other oneMod on _id is not allowed 发生在尝试根据对象的 id 更新对象而不首先删除它时。

    我还发现了这个github issue,它试图解释一个解决方案。它明确指出:

    注意不要将现有模型实例用于更新子句 (这不起作用,并可能导致奇怪的行为,如无限循环)。 此外,确保更新子句没有 _id 属性, 这会导致 Mongo 返回“Mod on _id not allowed”错误。

    解决方案似乎是执行以下操作:

    var upsertData = my_visit.toObject();
    
    console.log(req.body.id); // OK
    
    delete upsertData._id;
    
    models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) {
        if(err) { throw err; }
        //...
    }
    

    顺便说一句,您可能可以重写您的路线以在没有 if-else 子句的情况下同时进行创建和更新。 update() 有一个额外的选项 upsert,根据文档:

    upsert (boolean) 如果文档不匹配,是否创建文档 (false)

    【讨论】:

      【解决方案2】:

      这是我的解决方案:

      routes/router.js
      router.patch('/user/:id', userController.updateUser)
      
      exports.updateUser  =  async(req, res) => {
      
      
      
      const  updates  =  Object.keys(req.body)
      
      const  allowedUpdates  = ['name', 'email', 'password', 'age']
      
      const  isValidOperation  =  updates.every((update) =>  allowedUpdates.includes(update))
      
      
      
      if (!isValidOperation) {
      
      return  res.status(400).send('Invalid updates!')
      
      }
      
      
      
      try {
      
      const  user  =  await  UserModel.findByIdAndUpdate(req.params.id, req.body, { new:  true, runValidators:  true })
      
      
      
      if (!user) {
      
      return  res.status(404).send()
      
      }
      
      
      
      res.status(201).send(user)
      
      } catch (error) {
      
      res.status(400).send(error)
      
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-12
        • 2017-10-09
        • 2014-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 2015-01-09
        相关资源
        最近更新 更多