【问题标题】:How to force Mongoose to ignore __v if passed?如果通过,如何强制 Mongoose 忽略 __v?
【发布时间】:2018-08-13 10:03:00
【问题描述】:

使用 mongoose 和 Express 作为基本数据端点,我在 CRUD 操作的 Update 部分遇到问题。

在 Postman 中测试更新路径有效,但是当我从我的 Angular 应用程序中尝试时,它会返回:

MongoError: 更新路径 '__v' 会在 '__v' 处产生冲突 在 C:\Users\rutherfordc.AA\Documents\GitHub\techInventory\node_modules\mongoose\node_modules\mongodb-core\lib\conne 行动\pool.js:595:61 在 authenticateStragglers (C:\Users\rutherfordc.AA\Documents\GitHub\techInventory\node_modules\mongoose\node_module s\mongodb-core\lib\connection\pool.js:513:16) 在 Connection.messageHandler (C:\Users\rutherfordc.AA\Documents\GitHub\techInventory\node_modules\mongoose\node_mod ules\mongodb-core\lib\connection\pool.js:549:5) 在 emitMessageHandler (C:\Users\rutherfordc.AA\Documents\GitHub\techInventory\node_modules\mongoose\node_modules\mo ngodb-core\lib\connection\connection.js:309:10) 在套接字。 (C:\Users\rutherfordc.AA\Documents\GitHub\techInventory\node_modules\mongoose\node_modules\mo ngodb-core\lib\connection\connection.js:452:17) 在 Socket.emit (events.js:160:13) 在 addChunk (_stream_readable.js:269:12) 在 readableAddChunk (_stream_readable.js:256:11) 在 Socket.Readable.push (_stream_readable.js:213:10) 在 TCP.onread (net.js:602:20)

我真的不想更新__v,但我不明白为什么会触发它。如何强制忽略它?

这是我的更新方法:

  update(req,res){
    let _computer = req.body;
    let _id = req.params.computerId;
    Computer.findOneAndUpdate({'_id':_id}, _computer, {upsert: true}, (err, uc) => {
      if(err){
        log.error(err);
        res.status(500).send(err);
      }else{
        res.status(200).send(uc);
      }
    });
  }

【问题讨论】:

  • 请求正文中是否发送了__v
  • 是的,我试图阻止它在初始读取请求中发送到客户端,或者在从客户端发送补丁请求之前将其删除。
  • 在致电findOneAndUpdate 之前,您是否尝试过delete _computer.__v?您还可以尝试在您的查找查询上设置挂钩,以从返回的结果中排除 __v,这样 __v 如果适用于您的情况,就永远不会到达您的前端。
  • @foxinatardis 后者将是理想的。所以我的read()readOne() 处理程序在res.send() 之前执行delete obj.__v;
  • 你可以这样做。我建议使用一个中间件挂钩,它将普遍排除在查找查询之外。见:mongoosejs.com/docs/middleware.html

标签: javascript node.js mongodb mongoose


【解决方案1】:

您可以这样做以从 res.send() 发送的邮件中删除 __v

只需在Computer.findOneAndUpdate({'_id':_id},'-__v'); 中添加'-__v'

喜欢

 update(req,res){
    let _computer = req.body;
    let _id = req.params.computerId;
    Computer.findOneAndUpdate({'_id':_id},'-__v', _computer, {upsert: true}, (err, uc) => {
      if(err){
        log.error(err);
        res.status(500).send(err);
      }else{
        res.status(200).send(uc);
      }
    });
  }

您还可以显示和隐藏.find()findById() 中的任何字段。

隐藏使用'-field_name1 , -field_name2'

喜欢

Collection.find({},'-_id -__v');

要显示任何特定字段,请使用'field_name1 field_name2'

喜欢

collection.find({},'name number');

【讨论】:

【解决方案2】:

此问题已在 mongoose@5.0.16 中修复。有关详细信息,请参阅this link

您也可以在更新前从req.body 中删除__v

if (req.body.__v) {
  Reflect.deleteProperty(req.body, '__v');
}

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2010-10-11
    • 2016-01-09
    相关资源
    最近更新 更多