Search code examples
mongoosemongoose-populate

Populate does not seem to populate for all the array elements


Consider the code below:

const aux = await Fasta.find({}, "healthyTissue")
    .limit(1)
    .populate({
      //---------------------first level (healthy or tumor fasta file) ----------------
      path: "healthyTissue",
      model: "Hidden",

      options: {
        limit: 2
      },

      //---------------------    second level (hidden documents)       ----------------
      populate: {
        path: "children",
        options: {
          limit: 2
        },
        model: "FastaElement"
      }
    });

This is the output:

enter image description here

The problem: just the first children is populated. I have double-checked the database, and it is not empty.

I feel that I have seen this problem, but I cannot remember where. Could anyone refresh my memory?


Solution

  • Try adding perDocumentLimit to your populate options: https://mongoosejs.com/docs/api/model.html#model_Model.populate

    For legacy reasons, limit with populate() may give incorrect results because it only executes a single query for every document being populated. If you set perDocumentLimit, Mongoose will ensure correct limit per document by executing a separate query for each document to populate().