Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loopback: distinct query

Tags:

loopbackjs

I am using Loopback to create Rest API. Need to fetch distinct data based on a particular column from a collection. I tried below, but it's not working, instead the below snippet is fetching duplicate data also:

this.app.models.location.find(
                {
                    distinct: ("regionName",
                    {state: st})
                }
                ,
                function(err, location){........}

'RegionName' is the property of 'location' collection and I need data only for selected states (state is another property of location collection) which is represented by 'st'. Thanks.

like image 310
Heena Ghai Avatar asked Oct 20 '15 06:10

Heena Ghai


2 Answers

I have the answer in the following two examples:

1.) No query, just distinct on the "name" field of the "Role" collection:

var roleCollection = user.app.models.Role.getDataSource().connector.collection(user.app.models.Role.modelName);
roleCollection.distinct( "name",
  function(err, records) {
    if(err) {
      return cb(err);
    } else {
      return cb(null, records);
    }
  });

2.) With a query, distinct on the "name" field of the "Role" collection leaving out any role with the name of "admin":

var roleCollection = user.app.models.Role.getDataSource().connector.collection(user.app.models.Role.modelName);
roleCollection.distinct( "name", { name: { $ne: 'admin' } },
  function(err, records) {
    if(err) {
      return cb(err);
    } else {
      return cb(null, records);
    }
  });

Loopback.io v2.29.1

like image 104
TWright Avatar answered Oct 16 '22 17:10

TWright


I have this working now in my project.

Here is some example code (to help explain your question) that should do what you need...

// Distinct regions

Locations.regions = function (cb) {
  console.log('Locations.build');
  var ds = Locations.app.datasources.myDS;
  var sql = "SELECT DISTINCT region FROM Locations ORDER BY region"; // here you write your sql query.

  ds.connector.execute(sql, [], function (err, regions) {

    if (err) {
      cb(err, null);
    } else {
      cb(null, regions);
    }

  });

};

Locations.remoteMethod(
  'regions', {
    http: {
      path: '/regions',
      verb: 'get'
    },
    returns: {
      root: true,
      type: 'object'
    }
  }
);

** Note: this is for MySQL, but you should be able to modify the query for other connectors **

like image 37
joseph_carney Avatar answered Oct 16 '22 17:10

joseph_carney