接下来的问题,在我的应用程序中,我有帖子,每个帖子可以有一组评论。我正在尝试按日期对评论进行排序。我已经搜索并尝试了任何解决方案,但是没有一个对我有用。
我的尝试不起作用:
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 }
)
POST模型:
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。但这是一种复杂的方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句