Reputation: 625
Is it possible to get a find query return the result set in unordered manner. I have a table with following dataset
Id Country
1 Germany
2 Japan
3 China
4 England
5 USA
Upon firing the following query
Country.find({id:[1,5,3]}, function (err, result) {
res.json(result);
});
I get
1 Germany
3 China
5 USA
Is there a way to shutdown default sorting based on id and have the query result set in following expected order ?
1 Germany
5 USA
3 China
Upvotes: 2
Views: 88
Reputation: 3993
You cannot do this kind of sort in the find query. Indeed, you don't want to sort the query results but you want to retrieve them following the order of your array of ids. There is no order_by
rule that you could define here. The sort()
method of the query language allows you to sort using the values from a column in ascending or descending order. It seems that it's not what you are trying to do.
One solution would be to do n queries to retrieve each record independently and place the result in an array. It is not efficient and it would requires you to write some extra code to manage the data from the multiple asynchronous calls to the database.
A better solution would be to use lodash. Lodash comes with a lot of powerful functions to manipulate collections. It is perfect to perform this kind of task. Check at _.sortBy
var filter = [1,5,3];
Country.find({id:filter}, function (err, result) {
sortedResult = _.sortBy(result, function(country) {
return _.indexOf(filter, country.id);
});
res.json(sortedResult);
});
By default, lodash is globally available in sails.
Finally, you could use a pure JavaScript implementation to sort the result:
var filter = [1,5,3];
Country.find({id:filter}, function (err, result) {
result.sort(function(country_a, country_b) {
return filter.indexOf(country_a.id) - filter.indexOf(country_b.id);
})
res.json(result);
});
I usually first think about lodash to perform this kind of task, but the pure JavaScript implementation is fine here. Anyway, I think the lodash implementation is still a little more easy to read and in many other case, lodash will give you much more power.
Upvotes: 1