我有一个控制器,我试图查询上周最受欢迎的帖子,按最受欢迎的帖子排序,最大上限为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)
}
}
型
2条答案
按热度按时间bweufnob1#
试试这个聚合
字符串
q43xntqr2#
可以使用find方法。
字符串