【发布时间】:2014-10-14 23:11:22
【问题描述】:
我在猫鼬中有一个UserSchema 架构:
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: {}
});
我创建了一个虚拟的profile,它只返回公共个人资料的信息:
UserSchema
.virtual('profile')
.get(function() {
return {
'username': this.username,
'name': this.name,
'role': this.role
};
});
我的问题是当我发出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);
}
};
当然,我可以简单地将username、name 和role 放在那里,但在这种情况下我会重复代码。我可以避免吗?
【问题讨论】:
-
现在没有可以尝试的 Node.js/Mongo shell,但我认为如果您只选择('profile'),它会起作用。代码重复是什么意思?如果你改变你的虚拟,你必须在两个地方改变这个?
-
不,不幸的是,它只返回 _id 字段。是的,我不想在两个(或将来超过两个)地方更改相同的东西,以防万一。