Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!