Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2nd Create Schema and Model in NestJS with Mongoose #2

Open
misostack opened this issue Jul 27, 2022 · 0 comments
Open

2nd Create Schema and Model in NestJS with Mongoose #2

misostack opened this issue Jul 27, 2022 · 0 comments

Comments

@misostack
Copy link
Owner

2nd Create Schema and Model in NestJS with Mongoose

Define Schema

import * as mongoose from 'mongoose';
export type Schema = mongoose.Schema;
export class SchemaFactory {
  static createSchema(options: any): Schema {
    return new mongoose.Schema({
      ...options,
      createdAt: { type: Date, default: Date.now },
      updatedAt: { type: Date, default: Date.now },
    });
  }
}

Create Provider to inject Model ( created from Schema )

const CompanySchema = SchemaFactory.createSchema({
  name: { type: String, required: true, maxLength: 75 },
});

const companyProvider = {
      provide: `EXAMPLE_MODEL`,
      useFactory: (connection: Connection) =>
        connection.model('Company', CompanySchema ),
      inject: ['DatabaseConnection'],
    };

export const databaseProviders = [
  {
    provide: 'DatabaseConnection',
    useFactory: (): Promise<typeof mongoose> =>
      mongoose.connect(MONGODB_URL, mongooseOptions),
  },
];


@Module({
  imports: [],
  providers: [...databaseProviders, companyProvider],
  exports: [...databaseProviders, companyProvider],
})

Usage

@Module({
  imports: [DatabaseModule],
  controllers: [HealthController],
})
export class HealthModule {}

@Controller('health')
export class HealthController {
  constructor(
    @Inject('COMPANY_MODEL')
    private companyModel: Model<Company>,
  ) {}

  @Get()
  async check() {
    await this.companyModel.create({ name: 'dasd' });
    const totalOfCompany = await this.companyModel.count();
    console.log({ totalOfCompany });

    return {totalOfCompany}
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant