In Mongoose, the __v property is a version key that is added by default to MongoDB documents to represent the document's version. If you want to exclude this property from query results, there are multiple approaches to achieve this.
1. Exclude __v Property During Query Execution
When executing queries, you can exclude this field by setting __v: 0 in the projection parameter of the query.
javascriptModel.find({}, { __v: 0 }).then(result => { console.log(result); });
2. Use Schema Options to Globally Hide __v
When defining a Mongoose Schema, you can set versionKey to false, which hides the __v field in all instances of the model.
javascriptconst schema = new mongoose.Schema({ name: String }, { versionKey: false }); const Model = mongoose.model('Model', schema); const doc = new Model({ name: 'Hide __v example' }); console.log(doc); // `__v` will not be part of the document
3. Use Virtual Properties to Filter __v
Virtual properties are a highly flexible feature in Mongoose. You can define a virtual property to retrieve the document object excluding the __v field.
javascriptschema.virtual('documentWithoutVersionKey').get(function() { const obj = this.toObject(); delete obj.__v; return obj; });
After that, you can use this virtual property to retrieve the document object without the __v property.
4. Use toJSON and toObject Transformation Options
In the Schema definition, you can set the transform option for toJSON and toObject to exclude __v.
javascriptschema.set('toJSON', { transform: function(doc, ret, options) { delete ret.__v; return ret; } }); schema.set('toObject', { transform: function(doc, ret, options) { delete ret.__v; return ret; } });
This way, the __v field is automatically excluded whenever you call toJSON() or toObject().
Example
For instance, suppose you have a user model and you don't want to return the __v field in any API response. You can set versionKey: false when defining the user Schema:
javascriptconst userSchema = new mongoose.Schema({ username: String, email: String }, { versionKey: false }); const User = mongoose.model('User', userSchema);
This way, whenever you create an instance of the user model, it will not include the __v field.
Summary
In summary, hiding the __v property can be achieved either by dynamically excluding it during queries or by setting global options in the model definition based on project requirements.