Skip to content

Populate does not work with refPath and discriminated nested array #9153

@qqilihq

Description

@qqilihq

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

What is the current behavior?
We have a schema with (1) nested documents, which (2) use discriminators, and where (3) some of the discriminated types uses a refPath. When using Model.find(), these references are not populated, whereas when getting a single document with e.g. Model.findById(), the references are properly populated.

(probably related and/or regressions of earlier filed tickets #8837, #8731)

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

import mongoose from 'mongoose';

beforeAll(async () => mongoose.connect(process.env.MONGO_URL as string));

afterAll(async () => mongoose.disconnect());

describe('Mongoose array populate issue with refPath', () => {
  let Model: any;
  let doc2: any;

  beforeAll(async () => {
    const nested = new mongoose.Schema(
      {
        // nothing here
      },
      { discriminatorKey: 'type' }
    );

    const mySchema = new mongoose.Schema({
      title: { type: String },
      items: [nested]
    });

    const itemType = mySchema.path('items') as mongoose.Schema.Types.DocumentArray;

    itemType.discriminator(
      'link',
      new mongoose.Schema({
        fooType: { type: String },
        foo: {
          type: mongoose.Schema.Types.ObjectId,
          refPath: 'items.fooType' // this fails
          // ref: 'testModel' // this works
        }
      })
    );

    Model = mongoose.model<any>('testModel', mySchema);
    const doc1 = await Model.create({ title: 'doc1' });
    doc2 = await Model.create({
      title: 'doc2',
      items: [
        {
          type: 'link',
          fooType: 'testModel',
          foo: doc1._id
        }
      ]
    });
  });

  it('populates when using `find()`', async () => {
    const docs = await Model.find({}).sort({ title: 1 }).populate('items.foo').exec();
    expect(docs[1].items[0].foo.title).toEqual('doc1');
  });

  it('populates when using `findOne()`', async () => {
    const doc = await Model.findById(doc2._id).populate('items.foo').exec();
    expect(doc.items[0].foo.title).toEqual('doc1');
  });
});

What is the expected behavior?
Both tests should pass and the foo property should be properly populated.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

  • Mongoose 5.9.19
  • NodeJS v12.1.0
  • MongoDB 3.6.7

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