I want to get categories by limit, offset, orderBy viewers from VideoSchema
const CategoriesSchema = new Schema<ICategories>({
name: String,
image: String,
});
const VideoSchema = new Schema<IVideo>({
videoSource: String,
// from CategoriesSchema schema
category: {
name: String,
image: String,
},
viewers: Number,
});
What i do to get what i want:
const resolver = async ({ args: { limit, offset } }) => {
// there are 60k+ categories so request will be long
const categories = await CategoriesModel.find();
for (let i = 0; i < categories.length; i++) {
const streams = await VideosModel.find({ 'category.name': categories[i].name });
categories[i] = {
...categories[i],
// count viewers of current video
viewers: streams.reduce((acc, curr) => acc + curr.viewers, 0),
};
}
// sort by viewers, slice array by limit and offset
return categories.sort(({ viewers: viewersA = 0 }, { viewers: viewersB = 0 }) => viewersB - viewersA).slice(offset, limit);
},
I understand that request is not optimized, but I can't figure out how to do request by limit and offset and sort it by current viewers count. I know that in relational database like mysql i can use left join for that case, but don't understand how to do something like that with mongoose