Reputation: 23
following Problem, In my app i have Posts and each post can have an array of comments. I am trying to sort the comments by their date. I already searched for and already tried out any of the solutions but none of them worked for me.
My attempts not working:
const post = await Post.findById(id)
.populate({
path: 'comments',
options: { sort: { createdAt: -1 } },
})
const post = await Post.findById(id)
.sort({ 'comments.createdAt': -1 })
In my Post Model if reference the Comments model like following:
COMMENT SCHEMA
{
comment: { type: String, required: true },
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
},
{ timestamps: true }
)
POST MODEL:
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,
}
)
Thx for any help in advance
Upvotes: 2
Views: 258
Reputation: 721
The question is where you want to sort happen, to sort it on client side the easiest solution will be in place sorting of array comments
, since you are not referencing another schema document with ref
there is no need for populate
(lookup), just write another then
function like this:
const post = await Post.findById(p._id).then(result => {
result.comments.sort((a, b) => a.createdAt > b.createdAt ? -1 : 1);
return result;
})
To sort while fetching you should use the aggregate model function, and use the pattern of pipe stages: $match, $unwind, $sort, $group. But it is a way complicated.
Upvotes: 1