Skip to content

Model Populate behavior for perDocumentLimit option deviates from documentation #9175

Closed
@TerryvanWalen

Description

@TerryvanWalen

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
When using the perDocumentLimit option when populating documents, only the first document is populated. This seems contrary to what the documentation states.

If the current behavior is a bug, please provide the steps to reproduce.

export const docModel = new Schema({
  hash: {
    type: Schema.Types.String,
    index: true,
    required: true,
    unique: true,
  },
  subs: [
    {
      type: Schema.Types.ObjectId,
      ref: "SubDocModel",
    },
  ],
});

const docModel = mongo.model("DocModel", DocModel);
export default docModel;
export const subDocModel = new Schema({
  docHash: {
    type: Schema.Types.String,
    required: true,
  },
  subs: {
    type: [Schema.Types.String],
    required: true,
  },
});
const subDocModel = mongo.model("SubDocModel", SubDocModel);
export default subDocModel;
const docs = Model.find(query).sort({ hash: -1 });
const populatedDocs = await docs
  .populate({
    path: "subs",
    select: "subs -_id",
    perDocumentLimit: 2,
  })
  .lean();

console.log(populatedDocs)
> [
  {
    _id: 5ef4c738e491b7299d236252,
    subs: [ [Object], [Object] ],
    hash: '<hash>',
    __v: 0
  },
  {
    _id: 5ef4c738e491b7299d236251,
    subs: [],
    hash: '<hash>',
    __v: 0
  },
  {
    _id: 5ef4c738e491b7299d236250,
    subs: [],
    hash: '<hash>',
    __v: 0
  },

What is the expected behavior?
According to docs I understand that the returned documents should each hold exactly two subDocument objects.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
Mongoose: 5.9.20
Node: v12.13.1
MongoDB: v4.2.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions