Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda