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
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
Clean up:
There is Categories list, each category have number of viewers from VideoSchema (viewers field). If there is no video for that category then should have 0 viewers or if we have video for that category we print number of viewers from 0 to 2^32
Also I have changes in VideoSchema, for now its with ref to Categories
const VideoSchema = new Schema<IVideo>({
videoSource: String,
// from CategoriesSchema
category: {
ref: 'Categories'
},
viewers: Number,
});
