Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify returned fields in Node.js / Waterline?

I want to make a request like:

User.find().exec(function(){});

I know I can use toJSON in the model however I don't like this approach since sometimes I need different parameters. For instance if it's the logged in user I will return their email and other parameters. However if it the request fort he same data is made by a different user it would not include the email and a smaller subset of parameters.

I've also tried using:

User.find({}, {username:1}) ...
User.find({}, {fields: {username:1}});

But not having any luck. How can I specify the fields I need returned?

like image 764
Rob Avatar asked Jun 05 '14 19:06

Rob


3 Answers

So actually found a weird workaround for this. the fields param WILL work as long as you pass other params with it such as limit or order:

User.find({}, {fields: {username:1}}).limit(1);

Note that this will NOT work with findOne or any of the singular returning types. This means in your result callback you will need to do user[1].

Of course the other option is to just scrub your data on the way out, which is a pain if you are using a large list of items. So if anything this works for large lists where you might actually set limit(20) and for single items you can just explicitly return paras until select() is available.

like image 183
Rob Avatar answered Nov 15 '22 13:11

Rob


This is an update to the question, fields is no longer used in sails 11, please use select instead of fields.

Model.find({field: 'value'}, {select: ['id', 'name']})
  .paginate({page: 1}, {limit: 10})
  .exec(function(err, results) {
    if(err) {
      res.badRequest('reason');
    }
    res.json(results);
});
like image 36
jemiloii Avatar answered Nov 15 '22 15:11

jemiloii


Waterline does not currently support any "select" syntax; it always returns all fields for a model. It's currently in development and may make it into the next release, but for now the best way to do what you want would be to use model class methods to make custom finders. For example, User.findUser(criteria, cb) could find a user give criteria, and then check whether it was the logged-in user before deciding which data to return in the callback.

like image 5
sgress454 Avatar answered Nov 15 '22 14:11

sgress454