node.js mongodbnestjs
nest.js官方开发文档
npm i -g @nestjs/cli
nest new nest-api
选择是用npm还是yarn装依赖,我是直接回车选择npm
如果觉得慢此处可以取消,用vscode打开nest-api项目
终端再来安装依赖
npm i
等待安装完成
npm run start
nest g lib db @libs
输入@libs 回车
此时应该多了一个libs文件夹
npm i nestjs-typegoose @typegoose/typegoose mongoose @types/mongoose nestjs-mongoose-crud @nestjs/swagger swagger-ui-express
import { prop, modelOptions } from '@typegoose/typegoose';
import {ApiProperty} from '@nestjs/swagger';
// 给添加的数据加入时间戳
@modelOptions({
schemaOptions:{
timestamps:true
}
})
export class User{
@ApiProperty({description:'用户名',example:'user1'})
@prop()
username: string
@ApiProperty({description:'密码',example:'password1'})
@prop()
password: string
}
nest g mo -p users users
nest g co -p users users
import { Controller } from '@nestjs/common';
import { InjectModel } from 'nestjs-typegoose';
import {User} from '@libs/db/models/user.model'
import { Crud } from "nestjs-mongoose-crud";
import {ApiTags} from '@nestjs/swagger'
@Crud({
// User采用增删改查接口模式
model:User
})
@Controller('users')
@ApiTags('用户')
export class UsersController {
// 注入User模型
constructor(@InjectModel(User) private readonly model){}
}
import { Module, Global } from '@nestjs/common';
import { DbService } from './db.service';
import { TypegooseModule } from 'nestjs-typegoose';
import { User } from './models/user.model';
const models = TypegooseModule.forFeature([User]);
@Global()
@Module({
imports: [
TypegooseModule.forRoot(
'
mongodb+srv://root:[email protected]/nest-api?retryWrites=true&w=majority
',
{
useCreateIndex: true,
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false,
},
),
models,
],
providers: [DbService],
exports: [DbService, models],
})
export class DbModule {}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DbModule } from '@libs/db';
import { UsersModule } from './users/users.module';
@Module({
imports: [DbModule, UsersModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
const options = new DocumentBuilder()
.setTitle('nest后台API')
.setDescription('供后台管理界面调用的服务端API')
.setVersion('1.0')
// .addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api-docs', app, document);
await app.listen(3000);
console.log('http://localhost:3000');
console.log('http://localhost:3000/api-docs');
}
bootstrap();
npm run start
如图就是启动服务成功了
http://localhost:3000 就是你的本地接口地址
http://localhost:3000/api-docs 就是你的本地接口文档地址
看,写简单crud接口就是这么简单