2

I have a model like this:

module.exports = {
     attributes: {
         email: {
             type: 'email',
             required: true,
             unique: true
         },
         password: {
             type: 'string',
             minLength: 6,
             required: true
         },
         articles: {
           collection: ‘article',
           via: 'owners'
         },
         toJSON: function() {
             var obj = this.toObject();
             delete obj.password;
             return obj;
         }
     }
}

How can I query only the ‘email’ field without deleting others in the toJSON function?

The reason for this question is, if I have like thousands of articles with embedded images and so on, it would be a waste to collect all these articles and than delete them in the toJSON function, just to show the ‘email’ field only.

So, there must be a better way to achieve that. I hope you guys can answer me this question :)

UPDATE I forgot to say that I use blueprint.js as much as possible to avoid overriding create, delete, update,... in controllers.

AndaluZ
  • 1,195
  • 2
  • 11
  • 28

2 Answers2

6

It is not very well documented but Waterline provides a select criteria implemented here https://github.com/balderdashy/waterline-criteria/blob/master/lib/projections/select.js

I tested the following and it works. {} might be any query:

Model.find({}, {select: ['email']}).exec(function(err, result) {
    return res.send(result);
});
Upvote
  • 65,847
  • 122
  • 353
  • 577
0

It's possible to turn off auto-populating associated collections in models and hide little fields in the toJSON() function.

You can turn population off by setting populate: false in /config/blueprints.js

Than we can query users without articles like as usual: GET http://localhost:1337/user GET http://localhost:1337/user/id

and if you do want to show a collection of a certain user: GET http://localhost:1337/user/id/articles

another way is: GET http://localhost:1337/user?populate=[articles] This will show all the User attributes including articles.

If you have more collections: GET http://localhost:1337/user?populate=[articles, xCollection, yCollection]

GET http://localhost:1337/user?populate=[] GET http://localhost:1337/user?populate=false Both turn off population of collections.

Hope this helps.

Source: http://sailsjs.org/documentation/reference/blueprint-api/populate-where https://github.com/balderdashy/sails/issues/780 How to selectively populate waterline associations via query param in sails.js

Community
  • 1
  • 1
AndaluZ
  • 1,195
  • 2
  • 11
  • 28