skip to Main Content

I have a controller where I am trying to query the most popular posts within the last week, sorted by most popular, and has a max cap of 50 posts. I am trying to use the aggregate() method; however, I am not sure if I am doing it correctly. When I run the query In insomnia I get an error like so:

{
    "ok": 0,
    "code": 8000,
    "codeName": "AtlasError"
}

Here is my post model:

const postSchema = mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  message: {
    type: String,
    required: true
  },
  //replace creator with name
  name: String,
  creator: String,
  tags: [String],
  size: String,
  selectedFile: String,
  likes: {
    type: [String],
    default: [],
  },
  comments: {
    type: [String],
    default: []
  },
  createdAt: {
    type: Date,
    default: new Date(),
  },
   dogTreats: {
    type: Number,
    default: 0,
    required: false,
  }
});

and here is my controller/post.js

export const getPopular = async (req, res) => {
  //get current time
  let currentTime = new Date()
  //get from 7 days ago
  currentTime.setDate(currentTime.getDate()-7)
  console.log(currentTime)    // -> output 2022-09-04T19:29:39.612Z
  try {
    //sort posts by most likes and within 7 days ago, but with a max of 50 posts
    const mostPopular = await PostMessage.aggregate([{"$sort": { likes: -1}}, { "$limit": 50}, { "$gt": currentTime }])
    res.status(200).json(mostPopular)
} catch (error) {
    res.status(500).json(error)
}
}

2

Answers


  1. You can use find method. It is better to use here.

    If you need to reach a value from another table populated, aggregation is better to use. However, at here, find is the best way to reach datas.

     const mostPopular = await PostMessage.find({createdAt: {$gt : currentTime}}).sort({likes: -1}).limit(50)
    
    Login or Signup to reply.
  2. Try this aggregation

    export const getPopular = async (req, res) => {
      //get current time
      let currentTime = new Date()
      //get from 7 days ago
      currentTime.setDate(currentTime.getDate() - 7)
      console.log(currentTime) // -> output 2022-09-04T19:29:39.612Z
      try {
        //sort posts by most likes and within 7 days ago, but with a max of 50 posts
        const mostPopular = await PostMessage.aggregate([
          { $match: { createdAt: { $gt: currentTime } } },
          { $sort: { likes: -1 } },
          { $limit: 50 }
        ])
        res.status(200).json(mostPopular)
      } catch (error) {
        res.status(500).json(error)
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search