如何在Mongoose中从子数组中切片一定数量的元素?

5sxhfpxr  于 2023-10-19  发布在  Go
关注(0)|答案(2)|浏览(113)

有数百个项目,每个项目都包含评论。每个评论包含作者,内容,喜欢,回复。由于每个条目可能有数百条注解,我将注解的id嵌入到条目文档的子数组中。

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 }
);

当我获取一个项目时,我将为该项目加载10条最新评论。在客户端,有加载更多按钮。用户每次点击它,它都会加载10个以前的评论。我如何在Express.js中使用mongoose实现这一点呢?

ljsrvy3e

ljsrvy3e1#

const pageSize = 10; // Number of comments per page
const pageNumber = 1; // Page number (adjust as needed)

const pipeline = [
  // Match the relevant post
  { $match: { _id: ObjectId("your_post_id") } },

  // Project to retrieve only the comments array
  { $project: { _id: 0, comments: 1 } },

  // Unwind the comments array to prepare for sorting
  { $unwind: "$comments" },

  // Sort the comments by creation date in descending order
  { $sort: { "comments.created_at": -1 } },

  // Skip to the appropriate page
  { $skip: (pageNumber - 1) * pageSize },

  // Limit the number of comments per page
  { $limit: pageSize },

  // Group the comments back into an array
  { $group: { _id: null, comments: { $push: "$comments" } } }
];

const result = await db.posts.aggregate(pipeline).toArray();

// Extract the comments array from the result
const sortedComments = result.length > 0 ? result[0].comments : [];

如果comment对象中不存在createdAt,则可以跳过排序管道。

sqyvllje

sqyvllje2#

如果注解是排序的,你可以简单地使用$slice

const result = await posts.find(
  { _id: ObjectId("your_post_id")},
  { comments: { $slice: [ pageNumber * pageSize , pageSize  ] } } 
).populate('comments').exec();

其中pageSize = 10在您的情况下。
如果注解没有排序,可以使用管道$sortArray进行排序。对于当前的mongoDB版本,没有理由再次使用$unwind$group

相关问题