Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 200
EigenFool Avatar asked May 12 '19 21:05

EigenFool


People also ask

What is seeding in MongoDB?

Seeding a database is a process in which an initial set of data is provided to a database when it is being installed. In this post, you will learn how to get a working seed script setup for MongoDB databases using. Node.js. and. faker.js.

What is schema in NestJS?

Schemas are used to define Models. Models are responsible for creating and reading documents from the underlying MongoDB database. Schemas can be created with NestJS decorators, or with Mongoose itself manually.

Should we use mongoose?

Pros/Cons of using Mongoose: Biggest Pro is that it has the data validation built into it(requirements of what data you will allow to be added or to update your database). It will take some work to build that yourself. (but not THAT hard) It will abstract away most of the mongoDB code from the rest of the application.

How to create a nestjs application with Mongoose?

Mongoose module for Nest… So this is how your NestJS application should look at first, if you need help to create a NestJS application, please go to NestJS and get started with the CLI, it’s pretty straight forward. We are going to create the 4 entities, client, product, sale and user. Plus that we need to npm install the nestjs mongoose library.

How do I start a MongoDB database?

It's the easiest way to get a MongoDB database up and running. You'll need to get your MongoDB connection URI before you can run this script. For information on how to connect your application to MongoDB, check out the docs.

What is nestjs?

MongoDB (Mongoose) | NestJS - A progressive Node.js framework Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reactive Programming).

What is Database seeding and how does it work?

Database seeding is the initial seeding of a database with data. Seeding a database is a process in which an initial set of data is provided to a database when it is being installed. In this post, you will learn how to get a working seed script setup for MongoDB databases using Node.js and faker.js.


1 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: '[email protected]',
        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.

like image 168
Guilherme Reis Avatar answered Oct 21 '22 12:10

Guilherme Reis