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

362
Views
how to count an array object in a mongdb schema in nodejs?

I want to count the number of likes and comments both of which are arrays in the schema.The schema looks like this:

const PostSchema = new mongoose.Schema({
  text: {
    type: String,
    required: "Name is required",
  },

  photo: {
    data: Buffer,
    contentType: String,
  },
  likes: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
  comments: [
    {
      text: String,
      created: { type: Date, default: Date.now },
      postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
      likes: Number,
    },
  ],
  postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
  created: {
    type: Date,
    default: Date.now,
  },
});

As both likes and comments are arrays I want to count the number of elements inside them and I am doing it like this,I read about the aggregate function but cant figure out how to use it here as I have to iterate through all the post documents and fetch their likes and comments.

const leaderboard = (req, res) => {
  Post.find({}, function (err, docs) {
    docs.forEach(function (data) {
      var userid = data.postedBy;
      console.log(userid);
      var likes = data.likes.length;
      console.log(likes);
      var comments = data.comments.length;
      console.log(comments);
      const date2 = new Date();
      const diffTime = Math.abs(date2 - data.created);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      console.log(diffDays);
      const updated = User.findByIdAndUpdate(
        userid,
        {score: likes+comments+diffDays },
        function (errr, doc) {
          if (errr) {
            console.log(err);
          } else {
            console.log("Updated User : ", doc);
          }
        }
      );

I will really appreciate the help here,Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you can try project count the number of elements of comments and likes

Post.aggregate([
    {$project: {_id: 1, count: {$commentssize: '$comments'},count: {$sizelikes: '$likes'}}
])
over 4 years ago · Santiago Trujillo 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!