How do I paginate an array of _id in mongoose?

Viewed 1868

Currently, I have this confusion which is to paginate an array of items in a Schema.

So technically, every user has a cart and I want to paginate the cart's items. For example let say the cart has 18 items stored. I want to paginate the cart to only 5 items.

Here's the schema

const UserSchema = new Schema({
  email: { type: String, unique: true, lowercase: true},
  cart: [{
     type: Schema.Types.ObjectId, ref: 'Product'
  }],
});

Here's the route

My current Approach

router.get('/cart', (req, res, next) => {
  User.findOne({ _id: req.user._id })
    .populate({
    path: 'cart',
    options: { limit: 5 }
  })
  .exec((err, user) => {

    res.render('order/cart', { user: user });
  });
});

My current approach will definitely limit the items shown from 18 items to only 5 items, but this creates a new problem which now I can't calculate the total price of the cart because it only limit to 5 items per request.

enter image description here

1 Answers
Related