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

172
Vistas
Mongoose: Count array elements

I have the following Schema with a array of ObjectIds:

const userSchema = new Schema({
    ...
    article: [{
        type: mongoose.Schema.Types.ObjectId,
    }],
    ...
},

enter image description here

I will count the array elements in the example above the result should be 10.

I have tried the following but this doesn't worked for me. The req.query.id is the _id from the user and will filter the specific user with the matching article array.

const userData = User.aggregate(
    [
        {
            $match: {_id: id}
        },
        {
            $project: {article: {$size: '$article'}}
        },
    ]
)
console.log(res.json(userData));

The console.log(article.length) give me currently 0. How can I do this? Is the aggregate function the right choice or is a other way better to count elements of a array?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Not sure why to use aggregate when array of ids is already with user object.

Define articles field as reference:

const {Schema} = mongoose.Schema;
const {Types} = Schema;

const userSchema = new Schema({
    ...
    article: {
      type: [Types.ObjectId],
      ref: 'Article',
      index: true,
    },
    ...
});

// add virtual if You want
userSchema.virtual('articleCount').get(function () {
  return this.article.length;
});

and get them using populate:

const user = await User.findById(req.query.id).populate('articles');

console.log(user.article.length);

or simply have array of ids:

const user = await User.findById(req.query.id);

console.log(user.article.length);

make use of virtual field:

const user = await User.findById(req.query.id);

console.log(user.articleCount);

P.S. I use aggregate when I need to do complex post filter logic which in fact is aggregation. Think about it like You have resultset, but You want process resultset on db side to have more specific information which would be ineffective if You would do queries to db inside loop. Like if I need to get users which added specific article by specific day and partition them by hour.

about 4 years ago · Juan Pablo Isaza Denunciar
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