nestjs/mongoose

`@Plugin` decorator

Closed this issue · 1 comments

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

If I want to register a plugin for a schema, I need to use the forFeatureAsync() method like this:

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
      {
        name: Cat.name,
        useFactory: () => {
          const schema = CatsSchema;
          schema.plugin(require('mongoose-autopopulate'));
          return schema;
        },
      },
    ]),
  ],
})
export class AppModule {}

I think it can be made simpler.

Describe the solution you'd like

We can refer to typegoose to add a @Plugin decorator like this:

import { Prop, Schema, SchemaFactory, Plugin } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import * as AutoPopulate from 'mongoose-autopopulate';

export type CatDocument = Cat & Document;

@Plugin(AutoPopulate)
@Schema()
export class Cat {
  @Prop()
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Wish it was easier to use the mongoose plugin.

Let's track this here #1558