Run
Run

Reputation: 57176

Expressjs how to do pagination items inside an object?

How can I limit/ paginate the object array list in a document?

This is my document I stored in my mongoDB:

{
    "_id" : ObjectId("579639080a0b348a606d85ae"),
    "user_id" : "578899888a73ce23604200a7",
    "title" : "PM2.5",
    "data" : {
        "particles" : [ 
            "1", 
            "2", 
            "3", 
            "4", 
            "5"
        ],
        "timestamp" : [ 
            1469853926953.0, 
            1469853933742.0, 
            1469853937594.0, 
            1469853940779.0, 
            1469853943601.0
        ]
    },
    "created_at" : ISODate("2016-07-25T16:06:32.533Z"),
    "entries_number" : 5,
    "__v" : 0,
    "last_entry_at" : ISODate("2016-07-30T04:45:43.601Z")
}

I know I can use mongoose-paginate to limit all documents:

Model.paginate({}, { page: 3, limit: 10 }, function(err, result) {
  // result.docs
  // result.total
  // result.limit - 10
  // result.page - 3
  // result.pages
});

But I want to paginate/ limit the items in the data object actually:

     "data" : {
        "particles" : [ 
            "1", 
            "2", 
            "3", 
            "4", 
            "5"
        ],
        "timestamp" : [ 
            1469853926953.0, 
            1469853933742.0, 
            1469853937594.0, 
            1469853940779.0, 
            1469853943601.0
        ]
    },

Any ideas?

Upvotes: 0

Views: 524

Answers (1)

mayankbatra
mayankbatra

Reputation: 2678

Model.findOne({},  function(err, result) {
   result.data.particle = result.data.particle.slice(page*limit,page*limit+limit)
});

Can update to let you know how to structure it with multiple models, if you post some more code.

Upvotes: 1

Related Questions