I have a UserSchema
schema in mongoose:
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: {}
});
I've created a virtual profile
which returns only the information for the public profile:
UserSchema
.virtual('profile')
.get(function() {
return {
'username': this.username,
'name': this.name,
'role': this.role
};
});
My problem is how to get only this information when I'm making a find
request. Here's my code:
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);
}
};
Of course, I can simply put there username
, name
and role
but in that case I'd have code repetition. Can I avoid that?
Are you using the virtual profile
for any reason other than this find
? Your virtual really just specifies a number of fields, nothing more dynamic, so if you are just trying to select fields in the query I would stick with that (.select('username name role')
). If you want to make it reusable… just make the string a value in a module you can inject via require
. Then you can change it wherever you need to, and use it like select(profileFields)
.