Reputation: 2537
I have a collection fruits {name:'orange', id:1}....
and another one users
, user
s have document favorites: [1,2,3]
. I want to display the favourite
fruits at first and then the rest.
I can query twice like first with fruits.find({id: {$id:[user.favorites]}})
and then with not in
and then merge them.
Is there any other way to do it? Is there a possibility to pass custom function to sort
, if so. How can I do that?
Upvotes: 0
Views: 44
Reputation: 4091
No, Meteor doesn't allow a custom sort function. What you can do, is use the sortBy()
and contains()
functions from the underscore
library to sort your items:
var fruitsSorted = _.sortBy(fruits.find(selector).fetch(), (fruit) => {
if(_.contains(user.favorites, fruit.id)){
return 0;
}
return 1;
});
You now have a sorted array in fruitsSorted
.
Upvotes: 1
Reputation: 3333
Lets say you have queried fruits
collection for all fruits.
var fruits = [
{ name: 'orange', id: 1},
{ name: 'apple', id: 2},
{ name: 'banana', id: 3}
];
Now you can use sortBy
and includes
function from lodash
library to sort the fruits as per user favourites.
var sortedFruits = _.sortBy(fruits, function(fruit) {
return _.includes(user.favourites, fruit.id) ? 0 : 1;
});
Upvotes: 1