我有一个UserSchemamongoose架构:
var UserSchema = new Schema({
name: String,
username: String,
email: String,
role: {type: String, default: 'user'},
following: [{type: Schema.ObjectId, ref: 'User'}],
followers: [{type: Schema.ObjectId, ref: 'User'}],
hashedPassword: String,
provider: String,
salt: String,
facebook: {},
twitter: {},
github: {},
google: {}
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个虚拟profile,它只返回公共配置文件的信息:
UserSchema
.virtual('profile')
.get(function() {
return {
'username': this.username,
'name': this.name,
'role': this.role
};
});
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在我提出find请求时只获取此信息.这是我的代码:
UserSchema.statics = {
list: function (options, callback) {
var criteria = options.criteria || {};
this.find(criteria)
.select(/* What to put here? */)
.limit(options.perPage)
.skip(options.perPage * options.page)
.exec(callback);
}
};
Run Code Online (Sandbox Code Playgroud)
当然,我可以简单地放在那里username,name并且role但在这种情况下,我不得不码重复.我可以避免吗?
Gab*_* L. -1
profile除此之外,您是否出于其他原因使用虚拟设备find?您的虚拟实际上只是指定了许多字段,没有更多动态,因此如果您只是尝试在查询中选择字段,我会坚持使用(.select('username name role'))。如果您想使其可重用\xe2\x80\xa6,只需将该字符串作为模块中的值即可通过require. 然后您可以在任何需要的地方更改它,并像使用它一样select(profileFields)。
| 归档时间: |
|
| 查看次数: |
1779 次 |
| 最近记录: |