mongoDB查找当前日期起一周内最受欢迎的帖子

xvw2m8pv  于 11个月前  发布在  Go
关注(0)|答案(2)|浏览(124)

我有一个控制器,我试图查询上周最受欢迎的帖子,按最受欢迎的帖子排序,最大上限为50个帖子。我试图使用aggregate()方法;然而,我不确定我是否正确。当我在失眠症中运行查询时,我得到一个error,如下所示:

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

字符串
以下是我的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,
  }
});


这是我的控制器/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)
}
}

bweufnob

bweufnob1#

试试这个聚合

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)
  }
}

字符串

q43xntqr

q43xntqr2#

可以使用find方法。

const mostPopular = await PostMessage.find({createdAt: {$gt: currentTime}}).sort({likes: -1}).limit(50);

字符串

相关问题