Skip to content

Automatic denormalization / embedding #8530

@vkarpov15

Description

@vkarpov15

populate() makes it easy to pull in data from another collection, but in Mongoose 5.x you're on your own for embedding data.

If you're pulling a blog post's author from a 'User' collection, the below works fine.

const blogPostSchema = Schema({
      title: String,
      content: String,
      authorId: String,
      tags: [String]
    });

blogPostSchema.virtual('author', {
  ref: 'User',
  localField: 'authorId',
  foreignField: '_id',
  justOne: true
});

But if you want to embed author, it's up to you to set up middleware. Would be great if Mongoose could handle this:

const blogPostSchema = Schema({
      title: String,
      content: String,
      authorId: String,
      author: {
        type: UserSchema.pick(['name', 'email']),
        embed: 'User',
        localField: 'authorId',
        foreignField: '_id'
      },
      tags: [String]
    });

Metadata

Metadata

Assignees

No one assigned

    Labels

    new featureThis change adds new functionality, like a new method or class

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions