Friday 5 May 2017

Pagination on mongoDB aggregations [Node.js]

I have query something like this:

Message.aggregate([{
        "$match": {
          $or: [{
            "to": userId
          }, {
            "from": userId
          }]
        }
      },
      {
        "$sort": {
          "createDate": -1
        }
      },
      {
        "$group": {
          "_id": "$conversationId",
          "from": {
            "$first": "$from"
          },
          "to": {
            "$first": "$to"
          },
          "content": {
            "$first": "$content"
          },
          "createDate": {
            "$first": "$createDate"
          },
          "unreaded": {
            "$sum": {
              "$cond": {
                if: {
                  $and: [{
                      "$eq": [
                        "$unreaded", 1
                      ]
                    },
                    {
                      "$eq": ["$to", userId]
                    }
                  ]
                },
                then: 1,
                else: 0
              }
            }
          }

        }

      },
      {
        "$sort": {
          "createDate": -1
        }
      },
      {
        "$lookup": {
          "from": "users",
          "localField": "from",
          "foreignField": "_id",
          "as": "from"
        }
      },
      {
        "$lookup": {
          "from": "users",
          "localField": "to",
          "foreignField": "_id",
          "as": "to"
        }
      },
      {
        "$unwind": {
          "path": "$from"
        }
      },
      {
        "$unwind": {
          "path": "$to"
        }
      },
      {
        "$project": {
          "from.firstName": "$from.firstName",
          "from.lastName": "$from.lastName",
          "from.picture": "$from.picture",
          "to.firstName": "$to.firstName",
          "to.lastName": "$to.lastName",
          "to.picture": "$to.picture",
          "content": 1,
          "createDate": 1,
          "unreaded": 1,
          "reciver": {
            "$cond": {
              if: {
                "$eq": ["$from._id", mongoose.Types.ObjectId(userId)]
              },
              then: {
                "firstName": "$to.firstName",
                "lastName": "$to.lastName",
                "_id": "$to._id"
              },
              else: {
                "firstName": "$from.firstName",
                "lastName": "$from.lastName",
                "_id": "$from._id"
              }
            }
          }
        }
      },
      {
        "$limit": 50
      }

I am able now to limit records to 50 per request but problem is when I try to make pagination... I get this error when I try to add skip next to limit:

Error: Arguments must be aggregate pipeline operators

any idea how can I do that?



via Vladimir

No comments:

Post a Comment