Sails: the best way to exclude some data from a method in sails controller

Created on 14 Sep 2016  Â·  12Comments  Â·  Source: balderdashy/sails

Sails version: 0.12.3
Node version: 4.2.6
NPM version: 3.10.6
Operating system: Ubuntu 16.04
Database: MongoDB


I want's to exclude some data in some controller method and in other method i want's that data. I do it with forEach function right into method after finding that :

    nine: function (req, res) {
        Dore.find()
            .limit(9)
            .sort('createdAt DESC')
            .populate('file')
            .exec(function (err, sh) {
                if (err) {
                    return res.negotiate(err);
                } else {
                    console.log('before : ', sh);
                    sh.forEach(function (item, i) {
                        delete item.zaman;
                    });
                    console.log('after : ', sh);
                    return res.send(sh);
                }
            });
    },

I want to know how possible to do that with finding and do not included ever in finding so we don't need to remove that again with forEach.
tanks

orm question

Most helpful comment

Hi @hemedani - if you're looking to do this for simplicity / maintainability in your code, I'd suggest that the best approach is to stick with the approach you have, which is clear and explicit.

For example, here's how I'd do it:

nine: function(req, res) {

  // Find the 9 most recently created Dore records, and for
  // each one, populate the associated File (if there is one.)
  Dore.find()
  .limit(9)
  .sort('createdAt DESC')
  .populate('file')
  .exec(function(err, records) {
    if (err) {
      return res.serverError(err);
    }//--•

    // Now build the response data we'll use send back to
    // the requesting client.  To do this, we'll take the
    // raw array of records from the database and remove
    // all but a set of whitelisted properties from each one.
    //
    // > (alternatively, you could use `_.omit()` instead of `_.pick()` to do this
    // > as a blacklist instead.  Personally, I've found it's cleaner / easier to 
    // > maintain to only send down exactly what you actually need on a per-action basis.)
    var WHITELIST = [ 'id', 'createdAt', 'updatedAt', /*etc*/ ];
    var responseData = _.map(records, function (record) {
      return _.pick(record, WHITELIST);
    });

    // Send the modified array of records as a JSON response.
    return res.json(responseData);

  });//</Dore.find()>

},

On the other hand, if you're interested in projections because you've hit a performance bottleneck between your database server and your Sails cluster, you'll want to use projections. Currently, that is supported in Waterline 0.12, and will be exposed in Sails in the next major version release (Sails v1.0-- see ROADMAP.md in this repo for details). In the mean time, if you're fighting a production performance issue, I'd suggest targeting the problematic queries in your code base-- then using .native() to optimize on a per-query basis, as @karsasmus suggested (In Mongo, the hotspots will be in actions that do .find() calls on collections with very large fields you don't always need. But again, I'd recommend avoid optimizing that kind of thing until you're seeing a bottleneck based on real traffic).

Hope that helps a bit! And feel free to pop into the gitter if you have more questions

All 12 comments

Hi @hemedani! It looks like you may have removed some required elements from the initial comment template, without which I can't verify that this post meets our contribution guidelines. To re-open this issue, please copy the template from here, paste it at the beginning of your initial comment, and follow the instructions in the text. Then post a new comment (e.g. "ok, fixed!") so that I know to go back and check.

Sorry to be a hassle, but following these instructions ensures that we can help you in the best way possible and keep the Sails project running smoothly.

_If you feel this message is in error, or you want to debate the merits of my existence (sniffle), please contact [email protected]._

ok, fixed!

Sorry to be a hassle, but it looks like your issue is still missing some required info. Please double-check your initial comment and try again.

_If you feel this message is in error, or you want to debate the merits of my existence (sniffle), please contact [email protected]._

ok, fixed!

in the Query Option we have an select method but do not documented.
I try to use that with following format but don't working :

Model.find( {
            where: {},
            limit: 9,
            sort: 'createdAt DESC'
        },
        {
            select: [ 'id', 'createdAt' ]
        } )

and

Model.find( {
            where: {},
            limit: 9,
            sort: 'createdAt DESC',
            select: [ 'id', 'createdAt' ]
        } )

and

Model.find( {}, select: [ 'id', 'createdAt' ] )

Perhaps .native() is what you're looking for.

Tanks @karsasmus
But how can populate association after native query

I tested via sails console and everything was fine.
I wanted the fields id and createdAt from my User model and I got it.

User.find({select: ['id', 'createdAt']}).exec(console.log);

what's your database using ??

I'm using MongoDB

I'm using MongoDB, too.

Hi @hemedani - if you're looking to do this for simplicity / maintainability in your code, I'd suggest that the best approach is to stick with the approach you have, which is clear and explicit.

For example, here's how I'd do it:

nine: function(req, res) {

  // Find the 9 most recently created Dore records, and for
  // each one, populate the associated File (if there is one.)
  Dore.find()
  .limit(9)
  .sort('createdAt DESC')
  .populate('file')
  .exec(function(err, records) {
    if (err) {
      return res.serverError(err);
    }//--•

    // Now build the response data we'll use send back to
    // the requesting client.  To do this, we'll take the
    // raw array of records from the database and remove
    // all but a set of whitelisted properties from each one.
    //
    // > (alternatively, you could use `_.omit()` instead of `_.pick()` to do this
    // > as a blacklist instead.  Personally, I've found it's cleaner / easier to 
    // > maintain to only send down exactly what you actually need on a per-action basis.)
    var WHITELIST = [ 'id', 'createdAt', 'updatedAt', /*etc*/ ];
    var responseData = _.map(records, function (record) {
      return _.pick(record, WHITELIST);
    });

    // Send the modified array of records as a JSON response.
    return res.json(responseData);

  });//</Dore.find()>

},

On the other hand, if you're interested in projections because you've hit a performance bottleneck between your database server and your Sails cluster, you'll want to use projections. Currently, that is supported in Waterline 0.12, and will be exposed in Sails in the next major version release (Sails v1.0-- see ROADMAP.md in this repo for details). In the mean time, if you're fighting a production performance issue, I'd suggest targeting the problematic queries in your code base-- then using .native() to optimize on a per-query basis, as @karsasmus suggested (In Mongo, the hotspots will be in actions that do .find() calls on collections with very large fields you don't always need. But again, I'd recommend avoid optimizing that kind of thing until you're seeing a bottleneck based on real traffic).

Hope that helps a bit! And feel free to pop into the gitter if you have more questions

Thanks for posting, @hemedani. I'm a repo bot-- nice to meet you!

The issue queue in this repo is for verified bugs with documented features. Unfortunately, we can't leave some other types of issues marked as "open". This includes bug reports about undocumented features or unofficial plugins, as well as feature requests, questions, and commentary about the core framework. Please review our contribution guide for details.

If you're here looking for help and can't find it, visit StackOverflow, our Google Group or our chat room. But please do not let this disrupt future conversation in this issue! I am only marking it as "closed" to keep organized.

Thanks so much for your help!

If I am mistaken, and this issue is about a _critical bug with a documented feature_, please accept my sincerest apologies-- I am but a humble bot working to make GitHub a better place. If you open a new issue, a member of the core team will take a look ASAP.

Was this page helpful?
0 / 5 - 0 ratings