So, i have two mongoose models:
User: {
name: String,
..........
locations: []
}
Location: {
title: String,
.............
owner: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}
my lookup function in node, for User is something like:
api.find = function(filter, sort, skip, limit){
var callback = arguments[arguments.length - 1];
filter = treatFilter(filter);
sort = treatSort(sort);
if(callback && typeof callback === 'function'){
User.find(filter).sort(sort).skip(skip).limit(limit).exec(function(err, users){
if(users.length === 0){
callback(err, users);
}
for(var i = 0, complete = 0; i < users.length; i++){
(function(idx){
var user = users[idx];
var id = user.id;
Location.find({owner: id}, function(err, locations){
user.locations = locations;
if(++complete === users.length){
callback(err, users);
}
});
})(i);
}
});
}
};
what would my sort object have to be like so i could sort by number of locations?
Thanks, if you have any doubts i will be happy to explain my code
According to this post (mongoose - sort by array length)
You have to maintain a separate field that stores the location count -- not too much overhead but a little annoying to maintain
I looked into sorting by a virtual field, but this too is impossible and probably would be quite inefficient...