Can I use Sails native query with populate?

1.5k views Asked by At

I am using the native method of sails-mongo to query a collection. I need to use native to access some of the Mongo geospatial query features.

I would like to use the sails populate syntax to include associated models.

Is there a way to do this?

Here is an example of my existing code:

Trip.native(function(err, collection) {
    collection.find(
      {
        "locationTo": {
          "$near": {
            "$maxDistance": 80467.35439432222,
            "$geometry": {
              "type": "Point",
              "coordinates": [-117.133655, 32.720519]
            }
          }
        }
      }
    )
    .toArray(function(err, trips) {
      console.log("Trips nearby:", trips);
    });
});

Here is my Trip model for reference.

var Trip = {
  attributes: {
    owner: {
      model: 'User'
    },
    title: 'string',
    addressFrom: 'string',
    locationFrom: 'json',  // geoJson
    dateTimeDepart: 'datetime',
    dateTimeArrive: 'datetime',
    dateTimeReturn: 'datetime',
    addressTo: 'string',
    locationTo: 'json',  // geoJson
    driver: {
      model: 'User'
    },
    status: {
      type: 'string',
      defaultsTo: 'PENDING'
    }  
  }
}
2

There are 2 answers

1
Kevin Baker On

Thanks, I ended up doing it in two queries for now.

First, I build an array of matching ID's via the native query.

var tripIdList = trips.map(function (trip) {
  return trip._id
});

Second, I do a normal find query using the ID list. It's not a single query but works well. Thanks for the help

Trip.find(filter)
  .where({id: tripIdList})
  .populate('driver')
  .exec(function (err, trips) {
     console.log("Trips:", trips);  
  }
1
galactocalypse On

Would be helpful if you share the Trip model as well. If the field you wish to populate has type "collection" (not "array"), you should be able to populate it just fine.

Update: Alright, I got your question wrong. There doesn't seem to be any way of populating directly after a native call. There's really not much you can do with a native call as far as Waterline functions are concerned. I would suggest either running another query(Waterline) after you've fetched locationTo or populating the fields yourself since you only need to populate two of them(and that too from the same model). I can't think of anything that would suffice with a single query.