Search code examples
mongodbnestjstypeorm

Insert a user by default in MongoDB in Nest JS (Only when the app starts)


I am changing the project from expressjs to nestjs.

In express, I added an admin user to the database by default in app.ts.

like this:

public async addDefaultAdmin() {
    UserModel.find({ role: Roles.admin }).then(async (superAdmin) => {
      if (superAdmin.length === 0) {
        try {
          const newUser = new UserModel({...});
          await this.hashPassWord(newUser);
          await newUser.save();
          console.log("default admin successfully added.");
        } catch (error: any) {
          console.log(error);
        }
      }
    });
  }

I wanted to know how I can do this in NestJS? Does NestJS or typeOrm have a solution for this issue?


Solution

  • You may need to use lifecycle events. NestJS fires events during application bootstrapping and shutdown.

    According to doc, onApplicationBootstrap() event may be helpful in your case.

    Called once all modules have been initialized, but before listening for connections.

    However, NestJS does not expose a hook after the application starts listening, so in this case you need to run your custom function inside of bootstrap function right after the server could listen to a port.

    The pseudocode would be like this:

    // main.ts
    import { User } from '/path/to/user.entity';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      ...
      await app.listen(3000);
      let user = app.get(getRepositoryToken(User)); // You need to pass the entity file to typeorm
      await addDefaultAdmin(user); // Pass the user model, and call the function
    }
    
    bootstrap();