Nest (NestJS) 是一个用于构建高效、可扩展的 Node.js 服务器端应用的框架。它使用渐进式 JavaScript,构建并完全支持 TypeScript(但仍然允许开发者使用纯 JavaScript 进行编码)并结合了 OOP(面向对象编程)、FP(函数式编程)和 FRP(函数式反应式编程)的元素。
在幕后,Nest 使用强大的 HTTP 服务器框架,如 Express(默认),也可以选择配置为使用 Fastify!
Nest 在这些常见的 Node.js 框架(Express/Fastify)之上提供了一个抽象级别,但也直接向开发者公开了它们的 API。这使开发者可以自由使用可用于底层平台的无数第三方模块。
最近开发完一个小项目,使用了NestJS。目前Web3 项目(超 40% 的区块链节点服务采用)在国外(尤其是欧美地区)对 NestJS 的采用率较高,记录一下使用NestJS与MongoDB进行集成,并实现简单的CRUD操作。
技术栈如下:
前端 | 后端 | 数据库 |
---|---|---|
React 19 + Next.js 15 | Node.js 22 + NestJS 10 | MongoDB 7.0 |
项目结构如下:
my-nestjs-app/
├── node_modules/
├── src/ # 存放源代码文件
│ ├── main.ts # 应用程序的入口文件
│ ├── app/ # 根模块,负责引导整个应用程序
│ │ ├── app.controller.ts
│ │ ├── app.module.ts
│ │ └── app.service.ts
│ ├── users/ # 用户模块,包含控制器、服务和Schema
│ │ ├── users.controller.ts
│ │ ├── users.module.ts
│ │ ├── users.service.ts
│ │ └── schemas/
│ │ └── user.schema.ts
├── test/ # 测试文件
├── .dockerignore # Docker构建时忽略的文件
├── .env # 环境变量配置文件
├── Dockerfile # Docker配置文件
├── package.json # 项目依赖和脚本
└── tsconfig.json # TypeScript配置文件
一、环境准备与项目搭建
1.1 安装NestJS CLI
NestJS CLI是官方提供的命令行工具,快速创建和管理NestJS项目。确保开发环境已经安装了Node.js(推荐v16或更高版本),然后全局安装NestJS CLI:
npm i -g @nestjs/cli
1.2 创建新项目
使用CLI创建新项目:
nest new my-nestjs-app
cd my-nestjs-app
选择包管理器(npm/yarn/pnpm)后,CLI会自动创建项目结构并安装依赖。
1.3 安装MongoDB相关依赖
安装NestJS的MongoDB模块和Mongoose:
npm install @nestjs/mongoose mongoose
二、配置MongoDB连接
2.1 配置MongoDB连接
在app.module.ts中配置MongoDB连接:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { UsersModule } from './users/users.module';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost:27017/nestjs-mongodb'),
UsersModule,
],
})
export class AppModule {}
三、创建用户模块
3.1 创建用户模块
使用CLI创建一个新的模块:
nest g module users
3.2 创建用户Schema
在users目录下创建一个新的Schema文件user.schema.ts:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type UserDocument = User & Document;
@Schema()
export class User {
@Prop({ required: true })
name: string;
@Prop({ required: true })
email: string;
@Prop({ default: Date.now })
createdAt: Date;
}
export const UserSchema = SchemaFactory.createForClass(User);
3.3 注册Schema到模块
在users.module.ts中注册Schema:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from './schemas/user.schema';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}
四、实现CRUD操作
4.1 创建用户服务
在users.service.ts中实现CRUD逻辑:
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from './schemas/user.schema';
@Injectable()
export class UsersService {
constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {}
async findAll(): Promise<User[]> {
return this.userModel.find().exec();
}
async findOne(id: string): Promise<User> {
const user = await this.userModel.findById(id).exec();
if (!user) {
throw new NotFoundException('User not found');
}
return user;
}
async create(user: Partial<User>): Promise<User> {
const newUser = new this.userModel(user);
return newUser.save();
}
async update(id: string, user: Partial<User>): Promise<User> {
const updatedUser = await this.userModel.findByIdAndUpdate(id, user, { new: true }).exec();
if (!updatedUser) {
throw new NotFoundException('User not found');
}
return updatedUser;
}
async delete(id: string): Promise<void> {
const result = await this.userModel.findByIdAndDelete(id).exec();
if (!result) {
throw new NotFoundException('User not found');
}
}
}
4.2 创建用户控制器
在users.controller.ts中定义路由:
import { Controller, Get, Post, Put, Delete, Body, Param } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './schemas/user.schema';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
async findAll(): Promise<User[]> {
return this.usersService.findAll();
}
@Get(':id')
async findOne(@Param('id') id: string): Promise<User> {
return this.usersService.findOne(id);
}
@Post()
async create(@Body() user: Partial<User>): Promise<User> {
return this.usersService.create(user);
}
@Put(':id')
async update(@Param('id') id: string, @Body() user: Partial<User>): Promise<User> {
return this.usersService.update(id, user);
}
@Delete(':id')
async delete(@Param('id') id: string): Promise<void> {
return this.usersService.delete(id);
}
}
五、运行和测试
5.1 启动应用
运行应用:
npm run start:dev
5.2 测试API
使用Postman或curl测试API:
- GET /users:获取所有用户。
- GET /users/:id:获取单个用户。
- POST /users:创建新用户。
- PUT /users/:id:更新用户信息。
- DELETE /users/:id:删除用户。
六、总结
介绍了NestJS的核心概念和基础用法,包括模块、控制器、服务和依赖注入等。还包括了如何使用MongoDB连接NestJS,并实现了简单的CRUD操作,构建高效、可扩展的后端应用。