1

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!

1 Answer 1

2

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

Post.aggregate([
    {$project: {_id: 1, count: {$commentssize: '$comments'},count: {$sizelikes: '$likes'}}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.