1

i am trying to make a rest api with mongoose and i want to hide the __v property and i succesfully hidden it on find and findById by doing this:

Contact.find({}, '-__v', function(error, list) { });

Contact.findById(req.params.id, '-__v', function(error, item) { });

but when i use the create method

Contact.create(req.body, function(error, item) { });

it returns me the item added with __v property in it.

I ALSO tried this method using select: false on the schema like this

__v: {
  type: Number,
  select: false
}

This method also does the same thing, it hides the __v property from find and findById but also doesn't hide it from the crate method returned object.

Pacuraru Daniel
  • 1,207
  • 9
  • 30
  • 56

2 Answers2

5

In the schema you can set it as follows

 var Schema = new Schema({...}, { versionKey: false });
Rijad Rahim
  • 409
  • 4
  • 12
  • but i understand that's not recommended, so i wanted to keep the property but just hide it when i'm returning the datas on the endpoints – Pacuraru Daniel Nov 20 '17 at 07:39
  • hope this [link](https://stackoverflow.com/questions/13699784/mongoose-v-property-hide) can help you. :) – Rijad Rahim Nov 20 '17 at 07:59
2

You could also just use plain js after creating the file document:

Contact.create(req.body, function(error, item) { 
    delete item.__v;
    //other things
});
Sello Mkantjwa
  • 1,798
  • 1
  • 20
  • 36
  • this is an ok way to do it for now, i'm pretty new to mongo tho, but for some eason i cannot delete that property but i could do it if i clone the object and delete it from the cloned element, thank you very much for the answer – Pacuraru Daniel Nov 20 '17 at 14:00
  • 1
    @PacuraruDaniel I don't think you can delete it because `item` is a "special" Mongoose document object. You can convert it to an ordinary object with `item = item.toObject()`, for example. Or clone it like you do. – Mika Sundland Nov 20 '17 at 22:27
  • @MikaS yes, i came to the same conclusion as you did, that it's a special object, it's like a schema object because i can call methods on it that i implemented on the Contact schema, anyway thank you very much for the help – Pacuraru Daniel Nov 21 '17 at 10:11