简体   繁体   中英

How can i paginate an array of a document using node and mongoose or mongo?

{
"_id" : ObjectId("5f0083848f162b38900dc113"),
    "isEmailVerified" : false,
    "isProfileSetup" : true,
    "my_events" : [ 
        ObjectId("5f005a63b5524eb74813de11"), 
        ObjectId("5f005a5bb5524eb74813de0c"), 
        ObjectId("5f017dfcf8e6d8615cddfd6f")
    ]
}

I have this document in user's collection and i am trying to paginate the array my_events only. I am sorry if this is a stupid question.

Firstly is this possible to paginate this array without event fetching it completely from the db and if yes please share the way here.

{{url_local}}/api/event?user_id=5f0083848f162b38900dc113&page=1&limit=2

Above call should find the user with mentioned user_id and should return only these values:-

ObjectId("5f005a63b5524eb74813de11"),
ObjectId("5f005a5bb5524eb74813de0c")

And,

{{url_local}}/api/event?user_id=5f0083848f162b38900dc113&page=2&limit=2

it should return this:-

ObjectId("5f017dfcf8e6d8615cddfd6f")

This can be achieved with aggregation in MongoDB, pls check https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/

But in general, the advantage of paging will be lost as aggregations are heavy on the database, you should consider to change the document structure and create a collection for subdocuments and add a reference to your parent document if you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM