javascript - 按在 Mongoose 中创建的日期对引用的 Schema 进行排序
问题描述
以下问题,在我的应用程序中,我有帖子,每个帖子都可以有一系列评论。我正在尝试按日期对评论进行排序。我已经搜索并尝试了任何解决方案,但没有一个对我有用。
我的尝试不起作用:
const post = await Post.findById(id)
.populate({
path: 'comments',
options: { sort: { createdAt: -1 } },
})
const post = await Post.findById(id)
.sort({ 'comments.createdAt': -1 })
如果在我的帖子模型中引用评论模型,如下所示:
评论模式
{
comment: { type: String, required: true },
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
},
{ timestamps: true }
)
后模型:
const postSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
image: {
type: String,
},
text: {
type: String,
required: true,
},
workout: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Workout',
},
comments: [commentSchema],
numComments: {
type: Number,
required: true,
default: 0,
},
likes: [likeSchema],
numLikes: {
type: Number,
required: true,
default: 0,
},
},
{
timestamps: true,
}
)
感谢您提前提供任何帮助
解决方案
问题是您要在哪里排序,在客户端对其进行排序,最简单的解决方案是对数组进行排序comments
,因为您没有引用另一个ref
不需要populate
(查找)的模式文档,只需编写另一个then
函数,例如这个:
const post = await Post.findById(p._id).then(result => {
result.comments.sort((a, b) => a.createdAt > b.createdAt ? -1 : 1);
return result;
})
要在获取时排序,您应该使用聚合模型函数,并使用管道阶段的模式:$match、$unwind、$sort、$group。但这是一种复杂的方式。
推荐阅读
- python - 如何使用 StringVar() 命令从 Entry 命令读取的输入作为 tkinter 中的字符串
- bash - 循环文件并在模式之间操作文本
- cmake - CMake add_subdirectory 导致 CPack 仅构建源目录
- java - Jackson JSON对象反序列化中的异常
- sapui5 - 访问 OData 服务 VS 在程序中创建的数组返回的数组值 - SAP UI5
- php - json有错误但获取数据所以不能使用
- javascript - 如何在 Wordpress 中列出和重新排列或操作 Gutenberg 块类别
- c++ - 异或运算 C++/汇编
- java - 不同的对象数组元素引用同一个对象?
- dart - MQTT Dart 休息 API