在 Nest JS 的 MongoDB 中默认插入用户(仅当应用程序启动时)

问题描述 投票:0回答:2

我正在将项目从expressjs更改为nestjs。

在express中,我在app.ts中默认添加了一个admin用户到数据库中。

像这样:

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);
        }
      }
    });
  }

我想知道如何在 NestJS 中做到这一点? NestJS或typeOrm有解决这个问题的方法吗?

mongodb nestjs typeorm
2个回答
1
投票

您可能需要使用生命周期事件。 NestJS 在应用程序引导和关闭期间触发事件。

根据医生的说法,

onApplicationBootstrap()
活动可能对您的情况有帮助。

在所有模块初始化后但在侦听连接之前调用。

但是,NestJS 在应用程序开始监听后不会公开钩子,因此在这种情况下,您需要在服务器可以监听端口后立即在

bootstrap
函数内运行自定义函数。

伪代码如下:

// 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();

0
投票

您可以在您的服务中实现 OnApplicationBootstrap,如下所示:

在某些情况下你也可以使用 onModuleInit 。

Nestjs 文档的这一部分可以提供帮助!

© www.soinside.com 2019 - 2024. All rights reserved.