1

I am trying to fetch all the records but with selected fields, I have tried the following ways but none works:

Post.find( { where: {}, select: ['title'] } );

Post.find( {}, { fields: { title: 1 } } );

mahadazad
  • 541
  • 5
  • 19

3 Answers3

2

As this answer points out, the fields param "WILL work as long as you pass other params with it such as limit or order."

Alternatively, if you want this throughout your application, you could define a custom toJSON function for your model, under attributes. If not, you could still define it under some other (e.g. filter) and use map to return the custom objects instead of the default model. Remember to take care of the control flow while using map though. Use async/promises/raw logic to avoid returning before all objects are processed.

Community
  • 1
  • 1
galactocalypse
  • 1,905
  • 1
  • 14
  • 29
1

The issue has been resolved in sails-mongo latest version:

https://github.com/balderdashy/waterline/issues/1098

Thanks

mahadazad
  • 541
  • 5
  • 19
0

I've played with trying to get above answer to use limit or order to kick in the projection to no avail.

I did see this in the docs located here: http://sailsjs.org/documentation/reference/waterline-orm/models/native

With an out of the box solution for exactly what you're doing (pasted here for ease of use).

Pet.native(function(err, collection) {
    if (err) return res.serverError(err);

    collection.find({}, {
        name: true
    }).toArray(function (err, results) {
        if (err) return res.serverError(err);
        return res.ok(results);
   });
});

Swap out the response base things and change Pet to Post and, this ought to work in the sails console:

Post.native(function(err, collection) {
  if (err) throw new Error(err);

  collection.find({}, {
     title: true
  }).toArray(function (err, results) {
    if (err) throw new Error(err);
    console.log(results);
  });
});

You'll still get the _id field, and if you don't want that then hit the Mongo docs on not getting those hint(title: true, _id: false)hint

Hope this helps!

JoeManFoo
  • 339
  • 3
  • 11