Search code examples
expressmongoosemongoose-schemamern

Skip and limit on mongoose model sub-document/array


I recently started learning express and mongoose, but I'm not sure if I should be doing things the way I am. I followed a tutorial to handle posts, each post can have likes and comments, my model looks like this one from the tutorial. Mongoose Post Model

But I want lazy load my comments (like a Facebook post) when I open a post using skip and limit, the question is should I have the comments on another document or can I skip and limit inside of those comments?

Post.find({ id: req.params.id, comments: {skip: 0, limit: 10}})???


Solution

  • Take a look at this answer: Skip and Limit on nested array element

    As the example, you should use SLICE

    db.collection.find({}, {ObjectArray:{$slice:[0, 3]}})