2017-05-05 60 views
0

我有查詢是這樣的:分頁有關MongoDB聚合[Node.js的]

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 
     } 

我現在能夠記錄限制爲50%的要求,但問題是,當我試圖讓分頁...我當我嘗試添加跳過旁邊的限制時得到此錯誤:

Error: Arguments must be aggregate pipeline operators

任何想法我該怎麼做?

+0

您的參數無效。您應該將$ limit作爲聚合流水線數組中的一個元素。 –

回答

0

檢查你的參數並糾正錯誤。

Message.aggregate([{"$match": {$or: [{"to": userId}, {"from": userId}]}}, ..., {$skip: 1}, {$limit: 1}]) 
+0

'限制'的作品,但如何創建分頁? – Vladimir

+0

添加跳過運算符 –

+0

您的語法錯誤,沒有其他 –