PYP
PYP

Reputation: 125

Mongoose/Express - Counting number of likes

I have a Mongoose/Express app with a Blogs Schema, where other users can 'like' the blogs. In the Blogs Index, I would like to sort by the number of likes each blog has.

In the Blogs Schema, I have added a field called noOfLikes, but I'm unsure how to implement the count under the Blogs Controller (or elsewhere) to allow me to sort the records by noOfLikes.

Blog Schema with likes and noOfLikes fields (other fields removed for simplicity):

let blogSchema = new mongoose.Schema({
   comments: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }   
   ],
   likes: [
      {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User"
      }
   ],
   noOfLikes: { type: Number, default: 0 },
});

module.exports = mongoose.model("Blog", blogSchema);

Blog Controller, sorting by noOfLikes not currently working as unsure how to implement likes count in controller:

    async blogIndexAll (req, res, next) {

        blogs = await Blog.find().sort({ 'noOfLikes': -1 });

        res.render("blogViews/blog", {blogs, cloudinary, currentUser: req.user});
    },

Upvotes: 1

Views: 760

Answers (1)

ippi
ippi

Reputation: 10167

You could sort it without the help of mongoose after your query has executed.

For example:

blogs = await Blog.find({}).exec();
// Using Array.prototype.sort
blogs = blogs.sort( (a,b) => b.likes.length - a.likes.length );

Upvotes: 1

Related Questions