What is the proper way to do seed mongoDB in NestJS, using mongoose and taking advantage of my already defined schmas What is the proper way to do seed mongoDB in NestJS, using mongoose and taking advantage of my already defined schmas mongoose mongoose

What is the proper way to do seed mongoDB in NestJS, using mongoose and taking advantage of my already defined schmas


I've done using the nestjs-command library like that.

1. Install the library:

https://www.npmjs.com/package/nestjs-command

2. Then I've created a command to seed my userService like:

src/modules/user/seeds/user.seed.ts

import { Command, Positional } from 'nestjs-command';import { Injectable } from '@nestjs/common';import { UserService } from '../../../shared/services/user.service';@Injectable()export class UserSeed {constructor(    private readonly userService: UserService,) { }@Command({ command: 'create:user', describe: 'create a user', autoExit: true })async create() {    const user = await this.userService.create({        firstName: 'First name',        lastName: 'Last name',        mobile: 999999999,        email: 'test@test.com',        password: 'foo_b@r',    });    console.log(user);}}

3. Add that seed command into your module. I've created a SeedsModule in a shared folder to add more seeds in future

src/shared/seeds.module.ts

import { Module } from '@nestjs/common';import { CommandModule } from 'nestjs-command';import { UserSeed } from '../modules/user/seeds/user.seed';import { SharedModule } from './shared.module';@Module({    imports: [CommandModule, SharedModule],    providers: [UserSeed],    exports: [UserSeed],})export class SeedsModule {}

Btw I'm importing my userService into my SharedModule

4. Add the SeedsModule into your AppModule

On your AppModule usually at src/app.module.ts add the SeedsModule into imports

Final

If you followed the steps in the nestjs-command repo you should be able to run

npx nestjs-command create:user

That will bootstrap a new application and run that command and then seed to your mongo/mongoose

Hope that help others too.