首页 文章

如果传递,如何强制Mongoose忽略__v?

提问于
浏览
1

使用mongoose和Express作为基本数据 endpoints ,我遇到了CRUD操作的 Update 部分问题 .

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

MongoError:更新路径'__v'会在C:\ Users \ rutherfordc.AA \ Documents \ GitHub \ techInventory \ node_modules \ mongoose \ node_modules \ mongodb-core \ lib \ conne ction \ pool中的'__v'处产生冲突 . 在Connection.messageHandler的authenticateStragglers(C:\ Users \ rutherfordc.AA \ Documents \ GitHub \ techInventory \ node_modules \ mongoose \ node_module s \ mongodb-core \ lib \ connection \ pool.js:513:16)中的js:595:61 (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)在Socket上的\ 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)在TCP.onread(net.js:602)的Socket.Readable.push(_stream_readable.js:213:10)的addsAddChunk(_stream_readable.js:256:11)的addChunk(_stream_readable.js:269:12)处 . 20)

我真的不想更新 __v 但是我没有被触发't understand why it' . 我怎么能强迫它被忽略?

这是我的更新方法:

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

1 回答

  • 2

    您可以通过 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');

相关问题