CV肉饼王

Talk is cheap. Show me the code.

0%

Nestjs 使用 mongoose 连接 mongodb

1.安装依赖
1
2
npm install mongoose @nestjs/mongoose --save
npm install @types/mongoose --save-dev
2.在app.module.ts 中引入 Mongoose 的连接模块
1
2
3
4
5
6
7
8
9
10
11
12
13
// app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './server/user/user.module';

@Module({
imports: [MongooseModule.forRoot('mongodb://localhost/test'), UserModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
3.创建schema,定义数据表的格式
1
2
3
4
5
6
7
8
// user.schema.ts
import { Schema } from 'mongoose';

export const userSchema = new Schema({
_id: { type: String, required: true },
user_name: { type: String, required: true },
password: { type: String, required: true },
});
4.定义interface
1
2
3
4
5
6
7
import { Document } from 'mongoose';

export interface User extends Document {
readonly _id: string;
readonly user_name: string;
readonly password: string;
}
5.修改userModule
1
2
3
4
5
6
7
8
9
10
11
12
13
// user.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { userSchema } from './user.schema';

@Module({
imports: [MongooseModule.forFeature([{ name: 'Users', schema: userSchema }])],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
6.创建userService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateUserDTO, EditUserDTO } from './user.dto';
import { User } from './user.interface';

@Injectable()
export class UserService {
constructor(@InjectModel('Users') private readonly userModel: Model<User>) {}

/** 查找所有用户 */
async findAll(): Promise<User[]> {
return this.userModel.find();
}

/** 查找单个用户 */
async findOne(_id: string): Promise<User> {
return this.userModel.findById(_id);
}

/** 添加单个用户 */
async addOne(body: CreateUserDTO): Promise<void> {
await this.userModel.create(body);
}

/** 编辑单个用户 */
async editOne(_id: string, body: EditUserDTO): Promise<void> {
await this.userModel.findByIdAndUpdate(_id, body);
}

/** 删除单个用户 */
async deleteOne(_id: string): Promise<void> {
await this.userModel.findByIdAndDelete(_id);
}
}
7.配置userController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
Controller,
Body,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { CreateUserDTO, EditUserDTO } from './user.dto';
import { User } from './user.interface';
import { UserService } from './user.service';

interface UserResponse<T = unknown> {
code: number;
data?: T;
message: string;
}

@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}

@Get('users')
async findAll(): Promise<UserResponse<User[]>> {
return {
code: 200,
data: await this.userService.findAll(),
message: 'success',
};
}

@Get(':_id')
async findOne(@Param('_id') _id: string): Promise<UserResponse<User>> {
return {
code: 200,
data: await this.userService.findOne(_id),
message: 'success',
};
}

@Post()
async addOne(@Body() body: CreateUserDTO): Promise<UserResponse> {
await this.userService.addOne(body);
return {
code: 200,
message: 'success',
};
}

@Put(':_id')
async editOne(
@Param('_id') _id: string,
@Body() body: EditUserDTO,
): Promise<UserResponse> {
await this.userService.editOne(_id, body);
return {
code: 200,
message: 'Success.',
};
}

@Delete(':_id')
async deleteOne(@Param('_id') _id: string): Promise<UserResponse> {
await this.userService.deleteOne(_id);
return {
code: 200,
message: 'Success.',
};
}
}

参考文章:

写给前端的 Nest.js 教程——10分钟上手后端接口开发

Nestjs-Mongo

How To Build a Blog with Nest.js, MongoDB, and Vue.js