Answer a question

We are using NestJS with mongoose and want to seed mongoDB. Wondering what is the proper way to seed the database, and use the db schemas already defined to ensure the data seeded is valid and properly maintained.

Seeding at the module level (just before the definition of the Module) feels hacky and ends in threadpool being destroyed, and therefore all following mongo operations fail

Answers

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.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐