Skip to content

Getting a single object instead of an array while populating embedded objects with discriminators #9148

@ivan-burov

Description

@ivan-burov

Do you want to request a feature or report a bug?
a bug
What is the current behavior?
When an embed object is defined as a nested schema then everything is fine and an array of object ids populates an array of objects that ids belong to. But when it's defined through a discriminator then it returns the first item instead of an array of them
If the current behavior is a bug, please provide the steps to reproduce.

const mongoose = require('mongoose');
const Promise = require('bluebird');

const {Schema} = mongoose;

const ContentSchema = new Schema({
    name: String
});

const Content = mongoose.model('Content', ContentSchema);

const DataSchema = new Schema({
    alias: String
}, {
    discriminatorKey: 'type'
});

const ContentRelationSchema = new Schema({
    content: [{type: Schema.Types.ObjectId, ref: 'Content'}]
});

const PageSchema = new Schema({
    name: String,
    data: [DataSchema]
});

PageSchema.path('data').discriminator('content', ContentRelationSchema);

const Page = mongoose.model('Page', PageSchema);

mongoose
    .connect('mongodb://127.0.0.1:27017/test', {
        useNewUrlParser: true,
        promiseLibrary: Promise,
        useUnifiedTopology: true,
    })
    .then(async () => {
        const [contentA, contentB] = await Promise.all([
            Content.create({ name: 'A' }),
            Content.create({ name: 'B' }),
        ]);

        const { _id } = await Page.create({
            name: 'Index',
            data: [{
                alias: 'my_content',
                type: 'content',
                content: [contentA, contentB]
            }]
        });

        const page = await Page.findById(_id);
        console.log(page.data[0].content); // ["5eeb3e07148282899210d9c8","5eeb3e07148282899210d9c9"]

        await page.populate('data.content').execPopulate();
        console.log(page.data[0].content); // { _id: 5eeb3e07148282899210d9c8, name: 'A', __v: 0 }

    })
    .catch(console.log)
    .finally(() => mongoose.connection.close())

What is the expected behavior?
The population of arrays should return an array
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

  • node: 10.16.0
  • mongoose: 5.9.19
  • mongoDB: 4.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