windows系统 npm i -g @nestjs/cli nest new nest-mongo-demo (会自动安装依赖包) cd nest-mongo-demo npm run start:dev (运行) 0) 添加环境变量
# .env
ADMIN_PORT=3030
GAME_PORT=3040
-
添加swagger
npm i @nestjs/swagger swagger-ui-express -
修改代码
async function bootstrap() {
// const app = await NestFactory.create(AppModule);
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const options = new DocumentBuilder()
.setTitle('nest-mongo-demo项目')
.setDescription('供后台管理界面调用的服务端API接口文档')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api-docs', app, document);
const PORT = process.env.ADMIN_PORT || 3030;
await app.listen(PORT);
console.log(`http://localhost:${PORT}/api-docs`);
}
bootstrap();
-
api 文档地址 http://localhost:3030/api-docs/
-
docker安装mongo,并运行
docker pull mongo
docker run -p 27017:27017 --name nest-mongo-demo -d mongo:latest
docker ps 可以查看
5)安装 mongoose、 nestjs-typegoose、@typegoose/typegoose
6)连接Mongo数据库
先nest g mo db,生成db.model.ts文件,然后编写代码:
# db.model.ts 文件
import { Module } from '@nestjs/common';
import { TypegooseModule } from 'nestjs-typegoose';
@Module({
imports: [
TypegooseModule.forRoot('mongodb://localhost/nest-mongo-demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
}),
],
})
export class DbModule {}
7) 生成cats模块相关文件:nest g mo cats, nest g co cats, nest g s cats
8)顺便安装 class-validator, 并编写 cats.model.ts
(后续....)