Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
mongoose add a field to a document from another document

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

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda