Mongo
Nest 支持两种与 MongoDB 数据库集成的方式。你既可以使用 TypeORM 章节中介绍的 TypeORM 模块(它带有 MongoDB 连接器),也可以使用 Mongoose——最流行的 MongoDB 对象建模工具。本章介绍后者,使用的是专门的 @nestjs/mongoose 包。
想了解在 MongoDB 上完整的 CRUD REST API(含 id 校验、重复键错误、游标分页以及永不丢失的更新),请参阅用 Node.js 与 MongoDB 构建 CRUD REST API。
先安装所需的依赖:
$ npm i @nestjs/mongoose mongoose安装完成后,把 MongooseModule 导入根模块 AppModule:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {}forRoot() 方法接受的配置对象与 Mongoose 包中 mongoose.connect() 的相同,详见 Mongoose 连接指南。
模型注入
在 Mongoose 中,一切都派生自 Schema(模式)。每个 schema 映射到一个 MongoDB 集合(collection),并定义该集合中文档的形状。schema 用于定义 Model(模型)。模型负责从底层 MongoDB 数据库创建和读取文档。
你可以用 NestJS 装饰器创建 schema,也可以直接使用 Mongoose 手动创建。用装饰器创建 schema 能大幅减少样板代码,并提升整体可读性。
我们来定义 CatSchema:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
export type CatDocument = HydratedDocument<Cat>;
@Schema()
export class Cat {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}
export const CatSchema = SchemaFactory.createForClass(Cat);你也可以使用 DefinitionsFactory 类(来自 @nestjs/mongoose 包)生成原始的 schema 定义。这样就能手动修改由你提供的元数据生成的 schema 定义,适用于那些难以用装饰器完整表达的边缘场景。
@Schema() 装饰器把类标记为 schema 定义。它把 Cat 类映射到同名 MongoDB 集合,但末尾会多一个 "s",因此最终的集合名是 cats。该装饰器接受一个可选参数,即 schema 选项对象。可以把它理解为通常传给 mongoose.Schema 类构造函数的第二个参数(例如 new mongoose.Schema(_, options))。要了解可用的 schema 选项,请参阅 Mongoose schema 选项文档。
@Prop() 装饰器在文档中定义属性。例如,上面的 schema 定义声明了三个属性:name、age 和 breed。得益于 TypeScript 的元数据(以及反射)能力,这些属性的 schema 类型会被自动推断。但在更复杂的场景中,类型无法被隐式反射(例如数组或嵌套对象结构),此时必须显式指明类型,如下所示:
@Prop([String])
tags: string[];另外,@Prop() 装饰器也接受一个选项对象参数(详见可用的 schema 类型选项)。借助它,你可以指明属性是否必填、指定默认值,或将其标记为不可变。例如:
@Prop({ required: true })
name: string;要指定与其他模型的关系(以便后续 populate),同样使用 @Prop() 装饰器。例如,如果 Cat 有一个 Owner,且它存放在另一个名为 owners 的集合中,那么该属性应带上 type 和 ref 选项:
import mongoose from 'mongoose';
import { Owner } from '../owners/schemas/owner.schema.js';
// inside the class definition
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' })
owner: Owner;如果有多个 owner,属性配置应写成下面这样:
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' }] })
owners: Owner[];如果你并不打算总是 populate 到另一个集合的引用,可以考虑改用 mongoose.Types.ObjectId 作为类型:
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' })
// This ensures the field is not confused with a populated reference
owner: mongoose.Types.ObjectId;之后当你需要有选择地 populate 它时,使用一个指定了正确类型的仓储函数:
import { Owner } from './schemas/owner.schema.js';
// e.g. inside a service or repository
async findAllPopulated() {
return this.catModel.find().populate<{ owner: Owner }>("owner");
}如果没有可 populate 的外部文档,类型可能是 Owner | null,取决于你的 Mongoose 配置。也可能抛出错误,此时类型就是 Owner。
最后,你还可以把原始 schema 定义传给装饰器。例如,当某个属性表示一个未定义为类的嵌套对象时,这会很有用。为此,使用 @nestjs/mongoose 包中的 raw() 函数,如下所示:
@Prop(raw({
firstName: { type: String },
lastName: { type: String }
}))
details: Record<string, any>;另外,如果你不想使用装饰器,也可以手动定义 schema。例如:
export const CatSchema = new mongoose.Schema({
name: String,
age: Number,
breed: String,
});cat.schema 文件位于 cats 目录下的 schemas 文件夹中,CatsModule 也定义在那里。虽然你可以把 schema 文件放在任何喜欢的位置,但我们建议放在与其相关的领域对象附近,即相应的模块目录中。
来看一下 CatsModule:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsController } from './cats.controller.js';
import { CatsService } from './cats.service.js';
import { Cat, CatSchema } from './schemas/cat.schema.js';
@Module({
imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {}MongooseModule 提供了 forFeature() 方法用于配置模块,其中包括定义哪些模型应在当前作用域内注册。若要在其他模块中也能使用这些模型,请把 MongooseModule 加入 CatsModule 的 exports 数组,并在另一个模块中导入 CatsModule。
注册 schema 之后,就可以用 @InjectModel() 装饰器把 Cat 模型注入到 CatsService 中:
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat } from './schemas/cat.schema.js';
import { CreateCatDto } from './dto/create-cat.dto.js';
@Injectable()
export class CatsService {
constructor(@InjectModel(Cat.name) private catModel: Model<Cat>) {}
async create(createCatDto: CreateCatDto): Promise<Cat> {
const createdCat = new this.catModel(createCatDto);
return createdCat.save();
}
async findAll(): Promise<Cat[]> {
return this.catModel.find().exec();
}
}import { Model } from 'mongoose';
import { Injectable, Dependencies } from '@nestjs/common';
import { getModelToken } from '@nestjs/mongoose';
import { Cat } from './schemas/cat.schema.js';
@Injectable()
@Dependencies(getModelToken(Cat.name))
export class CatsService {
constructor(catModel) {
this.catModel = catModel;
}
async create(createCatDto) {
const createdCat = new this.catModel(createCatDto);
return createdCat.save();
}
async findAll() {
return this.catModel.find().exec();
}
}等待索引构建
Mongoose 编译模型时,会在后台创建该模型的集合并构建 schema 声明的索引。Nest 不会等待这项工作完成:应用可能在一个唯一索引尚不存在时就开始处理请求,而一次失败的构建(例如集合中已存在重复数据)也会被无声忽略。应用照常启动,并接受本应被该索引拒绝的重复数据。要让每个模型提供者在解析前等待 model.init(),请设置 waitForModelInit(在 @nestjs/mongoose 12.0.2 及更高版本中可用):
@Module({
imports: [MongooseModule.forRoot('mongodb://localhost/nest', { waitForModelInit: true })],
})
export class AppModule {}使用 forRootAsync() 时,在工厂函数中把该选项与 uri 一起返回。开启该选项后,注入的模型在注入时已经具备其集合与索引;而 init() 失败会让应用启动失败,并抛出对应的 MongoDB 错误:唯一索引下的重复键(E11000)、冲突的索引选项,或缺少创建索引的权限。启动过程还会等待索引构建本身完成,因此在大集合上新建索引会拖慢启动。
该选项也可以针对单个模型设置,放在 forFeature() 或 forFeatureAsync() 的条目中,此时它会覆盖连接的设置(两个方向都可以覆盖)。模型的 discriminators 会跟随该模型:
MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema, waitForModelInit: true }]),当连接尚未打开时会跳过等待,例如使用 lazyConnection: true 时。若设置 autoIndex: false,model.init() 不会构建索引,也就没有可等待的内容。在生产环境中,通常由某个发布步骤来构建索引,此时可用 Model.diffIndexes() 检查是否缺少索引。
连接
有时你可能需要访问原生的 Mongoose Connection 对象,例如在其上调用原生 API。用 @InjectConnection() 装饰器注入 Mongoose 连接,如下所示:
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
@Injectable()
export class CatsService {
constructor(@InjectConnection() private connection: Connection) {}
}会话
要用 Mongoose 开启会话,请通过 @InjectConnection() 注入数据库连接,而不是直接调用 mongoose.startSession()。这样能与 Nest 的依赖注入系统集成,并确保会话是在 Nest 管理的那个连接上开启的。
下面是一个开启会话的示例:
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
@Injectable()
export class CatsService {
constructor(@InjectConnection() private readonly connection: Connection) {}
async startTransaction() {
const session = await this.connection.startSession();
session.startTransaction();
// Your transaction logic here
}
}在这个示例中,@InjectConnection() 把 Mongoose 连接注入到服务中。之后你可以调用 connection.startSession() 开启新会话,并用它管理数据库事务,从而保证多个查询之间的原子性。开启事务后,记得根据业务逻辑提交或中止它,并在结束时关闭会话。
多数据库
有些项目需要多个数据库连接,本模块同样支持。要使用多个连接,先创建这些连接。在这种情况下,为连接命名是强制性的。
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/test', {
connectionName: 'cats',
}),
MongooseModule.forRoot('mongodb://localhost/users', {
connectionName: 'users',
}),
],
})
export class AppModule {}不要创建多个未命名或同名的连接,否则它们会相互覆盖。
这样设置之后,你必须告诉 MongooseModule.forFeature() 方法要使用哪个连接:
@Module({
imports: [
MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }], 'cats'),
],
})
export class CatsModule {}你也可以注入指定连接的 Connection 对象:
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
@Injectable()
export class CatsService {
constructor(@InjectConnection('cats') private connection: Connection) {}
}要把指定 Connection 注入到自定义提供者(例如工厂提供者)中,请使用 getConnectionToken() 函数,并把连接名作为参数传入:
{
provide: CatsService,
useFactory: (catsConnection: Connection) => {
return new CatsService(catsConnection);
},
inject: [getConnectionToken('cats')],
}要从具名连接注入模型,请把连接名作为第二个参数传给 @InjectModel() 装饰器:
@Injectable()
export class CatsService {
constructor(@InjectModel(Cat.name, 'cats') private catModel: Model<Cat>) {}
}@Injectable()
@Dependencies(getModelToken(Cat.name, 'cats'))
export class CatsService {
constructor(catModel) {
this.catModel = catModel;
}
}钩子(中间件)
中间件(也叫 pre 和 post 钩子)是在异步函数执行过程中被传入控制权的函数。中间件在 schema 层面指定,适合编写插件(参见 Mongoose 中间件文档)。在 Mongoose 中,编译模型之后再调用 pre() 或 post() 是不生效的。要在模型注册之前注册钩子,请使用 MongooseModule 的 forFeatureAsync() 方法配合工厂提供者(即 useFactory)。借助这种手法,你可以拿到 schema 对象,再用它的 pre() 或 post() 方法在该 schema 上注册钩子。例如:
@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: Cat.name,
useFactory: () => {
const schema = CatSchema;
schema.pre('save', function () {
console.log('Hello from pre save');
});
return schema;
},
},
]),
],
})
export class AppModule {}与其他工厂提供者一样,工厂函数可以是 async 的,并可通过 inject 注入依赖。
@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: Cat.name,
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
const schema = CatSchema;
schema.pre('save', function() {
console.log(
`${configService.get('APP_NAME')}: Hello from pre save`,
);
});
return schema;
},
inject: [ConfigService],
},
]),
],
})
export class AppModule {}插件
要为指定 schema 注册插件(plugin),请使用 forFeatureAsync() 方法:
import autopopulate from 'mongoose-autopopulate';
@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: Cat.name,
useFactory: () => {
const schema = CatSchema;
schema.plugin(autopopulate);
return schema;
},
},
]),
],
})
export class AppModule {}若要一次性为所有 schema 注册插件,请调用 Connection 对象的 .plugin() 方法。你必须在模型创建之前访问连接;为此可使用 connectionFactory 选项:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import autopopulate from 'mongoose-autopopulate';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/test', {
connectionFactory: (connection) => {
connection.plugin(autopopulate);
return connection;
}
}),
],
})
export class AppModule {}Discriminators
Discriminators(鉴别器)是一种 schema 继承机制。它让你可以在同一个底层 MongoDB 集合之上,拥有多个 schema 有重叠的模型。
假设你想在单个集合中跟踪不同类型的事件。每个事件都有时间戳。
@Schema({ discriminatorKey: 'kind' })
export class Event {
@Prop({
type: String,
required: true,
enum: [ClickedLinkEvent.name, SignUpEvent.name],
})
kind: string;
@Prop({ type: Date, required: true })
time: Date;
}
export const EventSchema = SchemaFactory.createForClass(Event);Mongoose 通过 "discriminator key"(鉴别键)来区分各 discriminator 模型,默认是 __t。Mongoose 会给你的 schema 添加一个名为 __t 的 String 路径,用它来跟踪某个文档是哪个 discriminator 的实例。
你也可以用 discriminatorKey 选项自定义用于鉴别的路径。
SignUpEvent 和 ClickedLinkEvent 的实例将与通用事件存储在同一个集合中。
现在定义 ClickedLinkEvent 类,如下所示:
@Schema()
export class ClickedLinkEvent {
kind: string;
time: Date;
@Prop({ type: String, required: true })
url: string;
}
export const ClickedLinkEventSchema = SchemaFactory.createForClass(ClickedLinkEvent);以及 SignUpEvent 类:
@Schema()
export class SignUpEvent {
kind: string;
time: Date;
@Prop({ type: String, required: true })
user: string;
}
export const SignUpEventSchema = SchemaFactory.createForClass(SignUpEvent);准备好这些之后,使用 discriminators 选项为指定 schema 注册 discriminator。它对 MongooseModule.forFeature() 和 MongooseModule.forFeatureAsync() 都适用:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forFeature([
{
name: Event.name,
schema: EventSchema,
discriminators: [
{ name: ClickedLinkEvent.name, schema: ClickedLinkEventSchema },
{ name: SignUpEvent.name, schema: SignUpEventSchema },
],
},
]),
]
})
export class EventsModule {}测试
对应用做单元测试时,通常希望避开任何数据库连接,这能让测试套件的搭建更简单、执行更快。但你的类可能依赖从连接实例中取出的模型。要解析这些类,可以创建 mock 模型。
为简化这一过程,@nestjs/mongoose 包暴露了 getModelToken() 函数,它根据模型名返回一个预置的注入令牌。使用该令牌,你可以用任何标准的自定义提供者手法(包括 useClass、useValue 和 useFactory)提供 mock 实现。例如:
@Module({
providers: [
CatsService,
{
provide: getModelToken(Cat.name),
useValue: catModel,
},
],
})
export class CatsModule {}在这个示例中,任何消费者通过 @InjectModel() 装饰器注入 Model<Cat> 时,都会得到这个硬编码的 catModel(对象实例)。
异步配置
当你需要异步而非静态地传入模块选项时,使用 forRootAsync() 方法。与大多数动态模块一样,Nest 提供了几种异步配置的写法。
一种写法是使用工厂函数:
MongooseModule.forRootAsync({
useFactory: () => ({
uri: 'mongodb://localhost/nest',
}),
});与其他工厂提供者一样,工厂函数可以是 async 的,并可通过 inject 注入依赖。
MongooseModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.get<string>('MONGODB_URI'),
}),
inject: [ConfigService],
});另一种写法是用类而不是工厂来配置 MongooseModule,如下所示:
MongooseModule.forRootAsync({
useClass: MongooseConfigService,
});上面的写法会在 MongooseModule 内部实例化 MongooseConfigService,并用它创建所需的选项对象。在这个示例中,MongooseConfigService 必须实现 MongooseOptionsFactory 接口,如下所示。MongooseModule 会在传入类的实例上调用 createMongooseOptions() 方法。
@Injectable()
export class MongooseConfigService implements MongooseOptionsFactory {
createMongooseOptions(): MongooseModuleOptions {
return {
uri: 'mongodb://localhost/nest',
};
}
}若要复用已有的选项提供者,而不是在 MongooseModule 内部创建私有副本,请使用 useExisting 写法。该提供者必须实现 MongooseOptionsFactory 接口:
MongooseModule.forRootAsync({
imports: [ConfigModule],
useExisting: ConfigService,
});连接事件
你可以使用 onConnectionCreate 配置选项监听 Mongoose 的连接事件。每个连接一被创建(在打开之前),Nest 就会以该连接为参数调用此函数,因此你可以为 connected、open、disconnected、reconnected 和 disconnecting 事件注册监听器,如下所示:
MongooseModule.forRoot('mongodb://localhost/test', {
onConnectionCreate: (connection: Connection) => {
connection.on('connected', () => console.log('connected'));
connection.on('open', () => console.log('open'));
connection.on('disconnected', () => console.log('disconnected'));
connection.on('reconnected', () => console.log('reconnected'));
connection.on('disconnecting', () => console.log('disconnecting'));
return connection;
},
}),这段代码建立了到 mongodb://localhost/test 处 MongoDB 数据库的连接。onConnectionCreate 选项设置了用于监控连接状态的事件监听器:
connected:连接成功建立时触发。open:连接完全打开、可以执行操作时触发。disconnected:连接丢失时调用。reconnected:断开后重新建立连接时调用。disconnecting:连接正在关闭的过程中触发。
你也可以在用 MongooseModule.forRootAsync() 创建的异步配置中使用 onConnectionCreate 属性:
MongooseModule.forRootAsync({
useFactory: () => ({
uri: 'mongodb://localhost/test',
onConnectionCreate: (connection: Connection) => {
// Register event listeners here
return connection;
},
}),
}),子文档
要在父文档中嵌套子文档,请这样定义 schema:
@Schema()
export class Name {
@Prop()
firstName: string;
@Prop()
lastName: string;
}
export const NameSchema = SchemaFactory.createForClass(Name);然后在父 schema 中引用该子文档:
@Schema()
export class Person {
@Prop(NameSchema)
name: Name;
}
export const PersonSchema = SchemaFactory.createForClass(Person);
export type PersonDocumentOverride = {
name: Types.Subdocument<Types.ObjectId> & Name;
};
export type PersonDocument = HydratedDocument<Person, PersonDocumentOverride>;要包含多个子文档,请使用子文档数组。并记得相应地覆盖属性类型:
@Schema()
export class Person {
@Prop([NameSchema])
name: Name[];
}
export const PersonSchema = SchemaFactory.createForClass(Person);
export type PersonDocumentOverride = {
name: Types.DocumentArray<Name>;
};
export type PersonDocument = HydratedDocument<Person, PersonDocumentOverride>;虚拟属性
在 Mongoose 中,virtual(虚拟属性)是存在于文档上但不会持久化到 MongoDB 的属性。它在每次被访问时动态计算。虚拟属性通常用于派生值或计算值,例如组合字段(如把 firstName 与 lastName 拼接成 fullName 属性),或创建依赖文档中已有数据的属性。
class Person {
@Prop()
firstName: string;
@Prop()
lastName: string;
@Virtual({
get: function (this: Person) {
return `${this.firstName} ${this.lastName}`;
},
})
fullName: string;
}@Virtual() 装饰器从 @nestjs/mongoose 包导入。
在这个示例中,fullName 虚拟属性由 firstName 和 lastName 派生而来。虽然访问它时表现得像普通属性,但它永远不会被保存到 MongoDB 文档中。
可观测性
NestJS Observe 是我们的官方可观测性平台,无需任何配置即可记录 Mongoose 查询。SDK 会对 Mongoose 底层的 mongodb 驱动做插桩(包括版本不一致时 Mongoose 安装的嵌套副本),因此每条命令都会以 span 的形式出现在执行它的提供者方法之下,慢请求也能看出它在等哪条查询。参见数据库查询与出站 HTTP。
示例
可运行的示例见 nestjs/nest 仓库。