Mongoose: find and select only fields specified in virtual

I have a UserSchema 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 created a virtual profile that only returns information for a 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 make a find query. Here is 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 just put username , name and role , but in this case I will have the code repeat. Can i avoid this?

+5
source share
2 answers

Do you use a virtual profile for any reason besides this find ? Your virtual one actually just points to several fields, no more dynamic, so if you were just trying to select fields in a query, I would stick with this ( .select('username name role') ). If you want to make it reusable ... just make the string a value in the module, which you can enter via require . Then you can change it wherever you need and use it as select(profileFields) .

0
source

According to mongooeys doc

Only non-virtual properties work both as part of queries and for selecting fields.

You can do it as follows:

 exports.show = function (req, res, next) { var userId = req.params.id; User.findById(userId, function (err, user) { if (err) { return next(err); } res.json(user.profile); }); }; 

But not this

 exports.devs = function (req, res, next) { User.find({role: 'developer'}, 'developer_profile', function (err, users) { if (err) { return res.status(500).send(err); } res.status(200).json(users); }); }; 

Here you can read here http://mongoosejs.com/docs/guide.html#virtuals

0
source

Source: https://habr.com/ru/post/1200824/


All Articles