There’re hundreds of items and each item contains comments. Each comment contains author, content, likes, replies. Since each item is likely to have hundreds of comments, I embedded comment’s id into sub-array inside item document.
const itemSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
index: true,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "Comment" }],
},
{ timestamps: true }
);
const commentSchema = new mongoose.Schema(
{
author: {
type: mongoose.Schema.Types.ObjectId,
ref: User,
required: true,
},
content: {
type: String,
required: true,
trim: true,
},
likes: {
type: [{ type: mongoose.Schema.Types.ObjectId, ref: User }],
default: Array,
},
replies: { type: [this], default: Array },
},
{ timestamps: true }
);
When I fetch an item, I am going to load 10 latest comments for that item. On the client side, there is load more button. Every time a user clicks on it, it loads 10 more previous comments. How can I achieve this with mongoose in Express.js?
2
Answers
You can skip sort pipeline if createdAt is not present in comment object.
If the comments are sorted, you can simply use
$slice
:Where pageSize = 10 in your case.
If the comments are not sorted, you can sort them using a pipeline with
$sortArray
. With current mongoDB versions there is no reason to$unwind
and$group
again.