在Mongoose中,__v
属性是一个版本键,默认情况下会添加到MongoDB文档中,用于表示文档的版本。如果要在查询时从结果中排除这个属性,有多种方法可以做到。
1. 查询时明确排除__v
属性
在执行查询时,可以通过在查询的projection
参数中设置__v: 0
来排除这个字段。
javascriptModel.find({}, { __v: 0 }).then(result => { console.log(result); });
2. 使用Schema的选项来全局隐藏__v
在定义Mongoose Schema时,可以设置versionKey
为false
,这样在该模型的所有实例中都会隐藏__v
字段。
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. 使用虚拟属性来过滤__v
虚拟属性是Mongoose中一个非常灵活的特性,你可以定义一个虚拟属性来获取除去__v
字段后的文档对象。
javascriptschema.virtual('documentWithoutVersionKey').get(function() { const obj = this.toObject(); delete obj.__v; return obj; });
之后,你可以使用这个虚拟属性来获取没有__v
属性的文档对象。
4. 使用toJSON
和toObject
转换选项
在Schema定义中,也可以通过设置toJSON
和toObject
的transform选项来排除__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; } });
这样在每次调用toJSON()
或toObject()
方法时,__v
字段都会被自动排除。
实例
例如,假设我有一个用户模型,并且我不希望在任何API响应中返回__v
字段,我可以在定义该用户Schema时设置versionKey: false
:
javascriptconst userSchema = new mongoose.Schema({ username: String, email: String }, { versionKey: false }); const User = mongoose.model('User', userSchema);
这样,无论何时创建用户模型的实例,都不会包含__v
字段。
总结来说,隐藏__v
属性可以根据项目要求,在查询时动态排除,或者在模型定义时通过Schema选项进行全局设置。