Skip to content
Advertisement

How to force Mongoose to ignore __v if passed?

Working with mongoose and Express for a basic data endpoint, and I’m having trouble with the Update portion of the CRUD operations.

Testing the Update path works in Postman, but when I try from my angular app, it returns this:

MongoError: Updating the path ‘__v’ would create a conflict at ‘__v’ at C:Usersrutherfordc.AADocumentsGitHubtechInventorynode_modulesmongoosenode_modulesmongodb-corelibconne ctionpool.js:595:61 at authenticateStragglers (C:Usersrutherfordc.AADocumentsGitHubtechInventorynode_modulesmongoosenode_module smongodb-corelibconnectionpool.js:513:16) at Connection.messageHandler (C:Usersrutherfordc.AADocumentsGitHubtechInventorynode_modulesmongoosenode_mod ulesmongodb-corelibconnectionpool.js:549:5) at emitMessageHandler (C:Usersrutherfordc.AADocumentsGitHubtechInventorynode_modulesmongoosenode_modulesmo ngodb-corelibconnectionconnection.js:309:10) at Socket. (C:Usersrutherfordc.AADocumentsGitHubtechInventorynode_modulesmongoosenode_modulesmo ngodb-corelibconnectionconnection.js:452:17) at Socket.emit (events.js:160:13) at addChunk (_stream_readable.js:269:12) at readableAddChunk (_stream_readable.js:256:11) at Socket.Readable.push (_stream_readable.js:213:10) at TCP.onread (net.js:602:20)

I don’t really want to update __v but I don’t understand why it’s being triggered. How can I force it to be ignored?

here’s my update method:

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

Advertisement

Answer

You can do this to remove __v from sending by res.send()

just add '-__v' in Computer.findOneAndUpdate({'_id':_id},'-__v');

like

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

You can also show and hide any field in .find() and findById().

To hide use '-field_name1 , -field_name2'

like

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

and to show any specific field use 'field_name1 field_name2'

like

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement