title: Limit query results after populating in MongoDB (Mongoose)
body: <p>I'm here to ask you about one problem that has kept me struggling in several projects and I don't know which is the best way to do it.</p>
  
  <p>The problem is:</p>
  
  <p>I am querying a MongoDB collection, called <em>Likes</em>, that has this schema:</p>
  
  <pre><code>  user: { type: Schema.Types.ObjectId, ref: 'User', required: true, index: true },
    product: { type: Schema.Types.ObjectId, ref: 'Product', index: true },
    list: { type: Schema.Types.ObjectId, ref: 'List', index: true },
    deleted: { type: Boolean, default: false }
  </code></pre>
  
  <p>I want to get all the items that belong to a certain user, not deleted yet, and paginated. And in the same query, I want to populate certain fields of that documents, so I do:</p>
  
  <pre><code>Like.find({ user: req.params.user_id, deleted: false })
    .skip((page - 1) * limit)
    .limit(limit)
    .populate([
      { path: 'product'},
      {
        path: 'list',
        match: { deleted: false },
        populate: [
          { path: 'items.product' },
          { path: 'users.user' }
        ]
      }
    ])
  </code></pre>
  
  <p>It works as expected. But the thing is, as we are matching non deleted lists in the populate functions, there are some documents with list property set to null.</p>
  
  <p>We want to return always as much documents as we can up to limit without any null list, but we can't filter them out. Because if the query returns 24 items, and we filter out 2 of them, there will be a gap between the number of returned results and the limit.</p>
  
  <p>Which is the best way to do it? I tried with aggregates also, but it gets messy because of the many things that we need to populate.</p>