“MongoDB -Aggregation Pagination” Code-Antworten

Pagination MongoDb

    def skiplimit(page_size, page_num):
        """returns a set of documents belonging to page number `page_num`
        where size of each page is `page_size`.
        """
        # Calculate number of documents to skip
        skips = page_size * (page_num - 1)

        # Skip and limit
        cursor = db['students'].find().skip(skips).limit(page_size)

        # Return documents
        return [x for x in cursor]
Odd Octopus

MongoDB -Aggregation Pagination

 let {
    allPostsPage = 1,
    followingPostsPage = 1,
    limit = 25,
    userId,
    fetchOthersPosts,
  } = req.query;
  const blockedUsers = await BlockUsers.aggregate([
    {
      $match: {
        $or: [
          { userId: mongoose.Types.ObjectId(userId) },
          { blockedUserId: mongoose.Types.ObjectId(userId) },
        ],
      },
    },
  ]);
  allPostsPage = parseInt(allPostsPage);
  followingPostsPage = parseInt(followingPostsPage);

  const blockedUserIds = [];
  blockedUsers.map((user) => {
    if (user.userId.toString() === userId.toString()) {
      blockedUserIds.push(user.blockedUserId);
    } else if (user.blockedUserId.toString() === userId.toString()) {
      blockedUserIds.push(user.userId);
    }
  });

  let noMoreFollowingPosts = false;
  let posts = [];
  let fakeTotalPagesFlag = false;

  let initialPosts = [];

  const followingList = await Followers.aggregate([
    { $match: { following: mongoose.Types.ObjectId(userId) } },
    { $project: { userId: 1, _id: 0, requestAccepted: 1 } },
  ]);

  const followingListIds = []
  followingList.map((e) => {
    if (e.requestAccepted === true || !e.hasOwnProperty("requestAccepted")) {
      followingListIds.push(mongoose.Types.ObjectId(e.userId));
    }
  });

  let noFollowers = false;
  if (followingListIds.length < 1) {
    fetchOthersPosts = "true";
    noFollowers = true;
  }

  // let queryFilter=;

  if (fetchOthersPosts === "false") {

    posts = await Post.aggregate([
      {
        $lookup: {
          from: "users",
          let: { userId: "$userId" },
          pipeline: [
            {
              $match: {
                $expr: { $eq: ["$_id", "$$userId"] },
              },
            },
            { $project: { fullName: 1, userName: 1, email: 1, image: 1, privateAccount: 1 } },
          ],
          as: "users",
        },
      },
      {
        $addFields: {
          userId: {
            $arrayElemAt: ["$users", 0],
          },
          dayssince: {
            $trunc: {
              $divide: [
                { $subtract: [new Date(), "$createdAt"] },
                1000 * 60 * 60 * 24,
              ],
            },
          },
        },
      },
      {
        $match: {
          $or: [
            { "userId._id": { $in: followingListIds } },
            {
              $and: [
                { "userId._id": mongoose.Types.ObjectId(userId) },
                { dayssince: { $lt: 2 } },
              ],
            },
          ],
        },
      },
      {
        $lookup: {
          from: "ingredients",
          localField: "ingredients.id",
          foreignField: "_id",
          as: "output"
        }
      },
      {
        $addFields: {
          "ingredients.name": "$output.name"
        }
      },
      { $project: { output: 0, postLikes: 0, userLiked: 0, ingredient: 0, dayssince: 0, users: 0, comments: 0, image: 0, video: 0 } },
      { $sort: { createdAt: -1 } },
      {
        $facet: {
          stage1: [{ $group: { _id: null, count: { $sum: 1 } } }],
          stage2: [
            {
              $skip: (followingPostsPage - 1) * limit,
            },
            { $limit: limit * 1 },
          ],
        },
      },
      {
        $unwind: {
          path: "$stage1",
        },
      },
      {
        $project: {
          count: "$stage1.count",
          data: "$stage2",
        },
      },
    ]);

    let filteredPostsCount = posts[0] ? posts[0].data.length : 0;

    let count = posts[0] ? posts[0].count : 0;
Bloody Bear

Ähnliche Antworten wie “MongoDB -Aggregation Pagination”

Fragen ähnlich wie “MongoDB -Aggregation Pagination”

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen