# 用 Node.js 和 MongoDB 构建 CRUD REST API

来源：https://docs.nestjs.com/tutorials/mongodb-crud-api

使用 NestJS 和 Mongoose，在 TypeScript 中用 Node.js 和 MongoDB 构建 CRUD REST API：校验输入、分页，以及永不丢失的更新。

该 API 管理一个商品目录：创建商品、逐页列出目录、读取单个商品、修改它的部分字段、删除它。这些工作大部分都很短。本教程把时间花在通常容易出错的地方：格式错误的 id 变成 500，重复的 SKU 同样如此，查询操作符被夹带进过滤器，列表在不同页之间重复或跳过商品，以及两个人同时编辑同一个商品并互相覆盖。

完成之后，这个 API 将能够：

- 通过 [`@nestjs/mongoose`](/data/mongodb) 把商品存入 MongoDB，在每个响应中用 `id` 代替 `_id`，并且不出现 `__v`。
- 用 [Zod](https://zod.dev/) schema 校验每个请求体、查询字符串和路由参数，并且凡是期望值的位置都拒绝 `$gt` 这类查询操作符。
- 对格式错误的 ObjectId 返回 400，对未知的 ObjectId 返回 404，对重复的 SKU 返回 409。
- 只更新请求发送的字段，并借助版本号拒绝基于过期副本的更新。
- 用游标逐页遍历目录，按类别、价格和库存过滤，并且只使用建有索引的排序方式。
- 配置无效时拒绝启动；它所依赖的唯一索引缺失或无法创建时，同样拒绝启动。
- 发送安全响应头，只接受来自你列出的来源的浏览器请求，用 OpenAPI 文档描述自身，响应健康检查，并在生产环境下写 JSON 日志。
- 在针对真实 MongoDB 服务器的测试中证明并发保证。

以下是各端点以及添加它们的小节：

| 端点 | 小节 |
| --- | --- |
| `POST /products`、`GET /products/:id`、`PATCH /products/:id`、`DELETE /products/:id` | [构建 CRUD 端点](/tutorials/mongodb-crud-api#build-the-crud-endpoints) |
| `GET /products` | [分页、过滤并排序列表](/tutorials/mongodb-crud-api#paginate-filter-and-sort-the-list) |
| `GET /health/live`、`GET /health/ready` | [添加健康检查](/tutorials/mongodb-crud-api#add-health-checks) |
| `GET /docs` | [组装应用](/tutorials/mongodb-crud-api#assemble-the-application) |

> info **提示** 完成后的应用位于 GitHub：[nestjs/example-mongodb-crud-api](https://github.com/nestjs/example-mongodb-crud-api)，其中包含测试和 CI 工作流。

你需要 Node.js 22 或更高版本，以及在本地运行 MongoDB 的 Docker。该 API 没有登录功能，这样 MongoDB 相关的部分才能保持为焦点；[接下来做什么](/tutorials/mongodb-crud-api#whats-next) 链接到了添加登录功能的教程。

#### 创建项目

使用 [Nest CLI](/cli/overview) 创建项目。`--minimal` 会生成一个代码集中在单个文件中的应用，本教程会替换该文件。它还会安装 [NestJS Observe SDK](/observability/sdk)，即 `@nestjs/observe`，并将其接入该文件；应用自身的文件则继续使用它：

```bash
$ npm i -g @nestjs/cli
$ nest new products-api --minimal
$ cd products-api
```

安装 [Node 适配器](/http/performance#node-adapter)，它直接在 `node:http` 上运行 Nest；再安装 Zod、[`@nestjs/config`](/application/configuration)、Mongoose 与 [`@nestjs/mongoose`](/data/mongodb)，以及用于 OpenAPI 文档和健康检查的包。CLI 安装的 Express 适配器已不再需要：

```bash
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/mongoose mongoose @nestjs/swagger @nestjs/terminus
$ npm i --save-dev @nestjs/testing vitest vite
```

在容器中启动 MongoDB：

```bash
$ docker run -d --name catalog-db -p 27017:27017 mongo:8
```

把它的 URI 写入项目根目录下的 `.env` 文件。`ConfigModule` 在启动时加载该文件：

```bash
MONGODB_URI=mongodb://localhost:27017/catalog
```

配置本身是一个 Zod schema。`ConfigModule` 在启动时用它校验环境变量，某个变量缺失或格式错误时，应用会拒绝启动：

```typescript
@@filename(src/config)
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  // 不用 z.url()：副本集的 URI 会列出多台主机，那不是合法的 URL。
  MONGODB_URI: z.string().regex(/^mongodb(\+srv)?:\/\/.+/, 'Expected a mongodb:// or mongodb+srv:// URI'),
  // 允许调用该 API 的浏览器来源，以逗号分隔。默认为空。
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
});

export type Env = z.infer<typeof envSchema>;
```

`MONGODB_URI` 没有用 `z.url()` 校验：副本集的连接字符串用逗号分隔列出各主机，例如 `mongodb://db1:27017,db2:27017/catalog`，`z.url()` 会拒绝它。

应用将包含这些文件：

<div class="file-tree">
  <div class="item">src</div>
  <div class="children">
    <div class="item">common</div>
    <div class="children">
      <div class="item">duplicate-key.filter.ts</div>
    </div>
    <div class="item">health</div>
    <div class="children">
      <div class="item">health.controller.ts</div>
      <div class="item">health.module.ts</div>
    </div>
    <div class="item">products</div>
    <div class="children">
      <div class="item">product.schema.ts</div>
      <div class="item">products.controller.ts</div>
      <div class="item">products.module.ts</div>
      <div class="item">products.schemas.ts</div>
      <div class="item">products.service.ts</div>
    </div>
    <div class="item">app.module.ts</div>
    <div class="item">config.ts</div>
    <div class="item">create-indexes.ts</div>
    <div class="item">main.ts</div>
  </div>
</div>

#### 用 Mongoose 为商品建模

在 Mongoose 中，schema 描述集合中的文档，模型负责读写它们。`@nestjs/mongoose` 从带装饰器的类构建 schema（参见 [模型注入](/data/mongodb#model-injection)）：

```typescript
@@filename(src/products/product.schema)
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import type { HydratedDocument } from 'mongoose';

@Schema({
  timestamps: true, // createdAt 和 updatedAt，由 Mongoose 在每次写入时设置
  versionKey: false, // 不生成 __v：下面的 `version` 才是客户端看到的版本
  toJSON: {
    virtuals: true, // 添加 `id`，即 ObjectId 的字符串形式
    transform: (_doc, ret: Record<string, unknown>) => {
      delete ret._id;
      return ret;
    },
  },
})
export class Product {
  @Prop({ required: true })
  sku: string;

  @Prop({ required: true })
  name: string;

  @Prop({ default: '' })
  description: string;

  @Prop({ required: true })
  category: string;

  // 金额以整数分表示：没有浮点舍入误差。
  @Prop({ required: true, min: 1 })
  price: number;

  @Prop({ required: true, min: 0 })
  stock: number;

  // 每次更新都会递增；客户端把它读到的版本号回传。
  @Prop({ required: true, default: 1 })
  version: number;

  createdAt: Date;
  updatedAt: Date;
}

export type ProductDocument = HydratedDocument<Product>;

export const ProductSchema = SchemaFactory.createForClass(Product);

// 两个商品不能共用同一个 SKU，无论有多少请求并发创建。
ProductSchema.index({ sku: 1 }, { unique: true });
// 列表允许的每种过滤与排序各有一个索引，最后以 _id 作为决胜字段。
ProductSchema.index({ createdAt: -1, _id: -1 });
ProductSchema.index({ price: 1, _id: 1 });
ProductSchema.index({ category: 1, createdAt: -1, _id: -1 });
ProductSchema.index({ category: 1, price: 1, _id: 1 });
```

- **是 `id`，不是 `_id`。** `toJSON` 选项添加 `id` 虚拟字段，即 ObjectId 的 24 字符字符串形式，并删除 `_id`。Nest 用 `JSON.stringify()` 序列化返回的文档，这会调用它的 `toJSON()`，因此每个包含商品的响应都有 `id`。
- **没有 `__v`。** Mongoose 自己的版本键只在 `save()` 时变化，而且默认只在数组变化时变化。该 API 需要一个在同一条语句中每次更新都会变化的版本号，所以它保留自己的 `version` 字段，并关闭 `__v`。
- **价格是整数，以分为单位。** `19.99` 无法精确存储为浮点数；`1999` 可以。
- **索引在 schema 中声明。** `sku` 上的唯一索引才是重复 SKU 不可能出现的原因：代码里的检查做不到这一点，因为两个请求可能在对方写入之前都通过检查。另外四个索引为 [列表](/tutorials/mongodb-crud-api#paginate-filter-and-sort-the-list) 服务。Mongoose 在应用启动时构建它们，除非关闭了 `autoIndex` 选项——生产环境正需要关闭（参见 [在生产环境创建索引](/tutorials/mongodb-crud-api#create-indexes-in-production)）。

#### 用 Zod 校验请求

来自客户端的每个值在到达 Mongoose 之前都要先经过 schema。以下是请求 schema：

```typescript
@@filename(src/products/products.schemas)
import { z } from 'zod';

// 24 个十六进制字符：其他任何值都会让 Mongoose 抛出 CastError，即 500。
export const objectId = z.string().regex(/^[0-9a-f]{24}$/, 'Invalid ObjectId');

// 转为大写，这样 `kb-001` 和 `KB-001` 对唯一索引而言是同一个 SKU。
const sku = z
  .string()
  .trim()
  .regex(/^[A-Za-z0-9-]{3,32}$/, 'Expected 3 to 32 letters, digits or dashes')
  .toUpperCase();
const name = z.string().trim().min(1).max(200);
const description = z.string().max(5_000);
const category = z.string().trim().toLowerCase().min(1).max(50);
// 以分为单位：1999 即 19.99。
const price = z.number().int().positive().max(10_000_000);
const stock = z.number().int().min(0);

export const createProductSchema = z.object({
  sku,
  name,
  description: description.default(''),
  category,
  price,
  stock,
});
export type CreateProductDto = z.infer<typeof createProductSchema>;

// 每个字段都可选，但都不允许 null，另外再加上客户端读到的版本号。
// 由各字段的 schema 组合而成：createProductSchema.partial() 会保留
// description 的默认值，从而在每次更新时清空它。
export const updateProductSchema = z
  .object({ sku, name, description, category, price, stock })
  .partial()
  .extend({ version: z.number().int().positive() })
  .refine((dto) => Object.keys(dto).length > 1, 'Nothing to update');
export type UpdateProductDto = z.infer<typeof updateProductSchema>;
```

稍后全局注册的 `StandardSchemaValidationPipe` 会校验每个声明了 `schema` 的参数，并把 schema 的输出传给处理器：去除首尾空白的字符串、大写的 SKU、小写的类别、description 的默认值。每个 schema 推导出的类型就是参数的类型，因此不需要 DTO 类（参见 [基于 schema 的校验](/application/validation#schema-based-validation)）。

##### 校验 MongoDB ObjectId

Mongoose 在构建查询时会把路由中的 id 转换为 ObjectId，当该字符串不是 ObjectId 时，它会抛出 `CastError`，最终以 500 Internal Server Error 的形式到达客户端：这仿佛在说服务器坏了，而实际上是请求坏了。`objectId` schema 则在任何查询执行之前就返回 400 Bad Request。一个格式合法但匹配不到任何商品的 id 是 404 Not Found：请求本身没问题，只是商品不存在。

> info **提示** `@nestjs/mongoose` 还导出了 `ParseObjectIdPipe` 和 `IsObjectIdPipe`，它们对无效 id 同样返回 400。而 schema 让每个参数都走同一套机制，并把 id 的模式写进 OpenAPI 文档。

##### 拒绝 NoSQL 操作符注入

MongoDB 查询是对象，而 JSON 请求体可以携带对象。如果请求体里的 `version` 原样进入更新的过滤器，客户端就可以发送这样的内容：

```json
{ "stock": 0, "version": { "$gte": 0 } }
```

该过滤器会匹配任意版本，于是那个防止 [丢失更新](/tutorials/mongodb-crud-api#prevent-lost-updates-with-a-version) 的检查就会放行一次过期写入。schema 就是防线：`version` 必须是数字，`name` 必须是字符串，因此在本该是值的位置放一个对象，会在任何查询构建之前就得到 400。未知属性，比如顶层的 `$where`，会被 `z.object()` 剥离（参见 [未知属性](/application/validation#unknown-properties)）。而服务自己逐字段地用经过校验的值构建每个过滤器：它从不把请求体或查询对象交给 Mongoose。

> info **提示** Mongoose 的 `sanitizeFilter` 选项是第二道防线：它把过滤器里任何带 `$` 键的对象包进 `$eq`，使其按字面匹配。这样你自己的操作符就需要用 `mongoose.trusted()` 标记。既然每个值都经过 schema 校验，本教程不需要这个选项。

#### 构建 CRUD 端点

服务用 `@InjectModel()` 注入的模型完成读写：

```typescript
@@filename(src/products/products.service)
import { ConflictException, Injectable, NotFoundException, type OnModuleInit } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import type { Model } from 'mongoose';
import { Product, type ProductDocument } from './product.schema.js';
import type { CreateProductDto, UpdateProductDto } from './products.schemas.js';

@Injectable()
export class ProductsService implements OnModuleInit {
  constructor(@InjectModel(Product.name) private readonly productModel: Model<Product>) {}

  async onModuleInit() {
    // 在开发环境和测试中，模型注入时索引已经建好（AppModule 中的 waitForModelInit）。
    // 关闭 autoIndex 时（生产环境），索引由发布步骤创建：如果没有创建，就拒绝启动。
    const { toCreate } = await this.productModel.diffIndexes();
    if (toCreate.length > 0) {
      throw new Error(`Missing indexes on products: ${JSON.stringify(toCreate)}. Run npm run db:indexes.`);
    }
  }

  create(dto: CreateProductDto): Promise<ProductDocument> {
    return this.productModel.create(dto);
  }

  async findOne(id: string): Promise<ProductDocument> {
    return (await this.productModel.findById(id)) ?? notFound();
  }

  async update(id: string, { version, ...changes }: UpdateProductDto): Promise<ProductDocument> {
    // 一条带条件的语句：只有当商品仍处于客户端读到的版本时它才匹配，
    // 而 $set 只写入客户端发送的字段。
    const product = await this.productModel.findOneAndUpdate(
      { _id: id, version },
      { $set: changes, $inc: { version: 1 } },
      { returnDocument: 'after', runValidators: true },
    );
    if (product) {
      return product;
    }
    // 没有任何匹配：要么商品不存在，要么别人先改了它。
    if (!(await this.productModel.exists({ _id: id }))) {
      notFound();
    }
    throw new ConflictException(`Product has changed since version ${version}`, { errorCode: 'VERSION_CONFLICT' });
  }

  async remove(id: string): Promise<void> {
    const { deletedCount } = await this.productModel.deleteOne({ _id: id });
    if (deletedCount === 0) {
      notFound();
    }
  }

  // list() 在下一节介绍。
}

function notFound(): never {
  throw new NotFoundException('Product not found');
}
```

- **`onModuleInit()` 检查索引。** `diffIndexes()` 把 schema 中的索引与集合中的索引做比较，只要缺一个，应用就拒绝启动。这在生产环境很重要，因为那里 Mongoose 不构建任何索引，而是由 [发布步骤](/tutorials/mongodb-crud-api#create-indexes-in-production) 来构建。在其他环境中，服务被创建时 Mongoose 已经建好了索引，因为连接的 `waitForModelInit` 选项会等待构建完成（参见 [组装应用](/tutorials/mongodb-crud-api#assemble-the-application)）。
- **`findOne()` 在 `findById()` 找不到时返回 404**。id 已经校验过，所以这属于「合法但未知」的情况。
- **`remove()` 检查 `deletedCount`**，取自执行删除的那条语句，而不是先读取商品。

##### 只更新客户端发送的字段

`update()` 发送一条带 `$set` 的 `findOneAndUpdate()`。Zod 会略去客户端没有发送的字段，因此 `$set` 只写入客户端确实发送的字段，不写其他字段：一个只改价格的 `PATCH` 会让名称、描述和库存保持原样，无论它们在此期间如何变化。有三件事会破坏这一点：

- **保存整个文档。** 读取商品、把请求体合并进去，再调用 `save()` 或 `replaceOne()`，会把读到的每个字段都写回去，包括另一个请求在此期间改过的字段。
- **更新 schema 中的默认值。** `createProductSchema.partial()` 会保留 `description` 的 `.default('')`，于是在每个没有发送描述的 `PATCH` 中清空描述。
- **`$set` 中的嵌套对象。** `$set` 替换字段的整个值：对于 `dimensions` 对象，一个只包含 `width` 的 `PATCH` 会删掉它的 `height`。要用点号路径设置嵌套对象的单个属性，例如 `'dimensions.width'`。

`null` 字段会得到 400，而不是存入 `null`；没有任何可更新内容的更新同样如此。`runValidators: true` 让 Mongoose 把 schema 自身的规则（例如 `stock` 上的 `min: 0`）也应用到更新上；没有它，Mongoose 只在 `create()` 和 `save()` 时检查这些规则。

##### 用版本号防止丢失更新

Ada 和 Bob 都打开了键盘的编辑表单，版本都是 1。Ada 改了价格；一分钟后，Bob 保存了他手上仍然持有的那份副本。没有版本号时，两个请求都会成功；如果 Bob 的表单发送了所有字段，Ada 改的价格就没了。所以每次更新都要说明它基于哪个版本。更新的过滤器同时匹配商品的 `_id` 和客户端发送的 `version`，并且同一条语句会递增 `version`。MongoDB 对文档原子地应用过滤器和更新，因此在两个基于版本 1 的更新中，恰好有一个能找到版本 1 的商品。另一个什么都不改，服务返回 409 Conflict，告诉客户端重新读取商品，让用户自行决定。第二个查询把这种情况与商品不存在（404）区分开。这个 409 带有 `errorCode`，客户端无需解析消息就能把它与重复 SKU 区分开（参见 [机器可读的错误码](/exception-filters#machine-readable-error-codes)）。

这就是乐观并发：用户查看表单期间没有任何东西被锁定。Mongoose 的 `optimisticConcurrency` schema 选项只对 `save()` 做同样的事，而 `save()` 先读文档再写回，需要两次往返；带条件的更新只需一次。文末的 [测试](/tutorials/mongodb-crud-api#test-it) 会同时发送十个基于同一版本的更新，并检查其中恰好一个被应用。

#### 分页、过滤并排序列表

`GET /products` 返回目录的一页，带有默认页大小和上限，这样没有任何请求会读取整个集合。以下是其余的请求 schema：

```typescript
@@filename(src/products/products.schemas)
// ...

// 游标对客户端是不透明的，但它仍然是客户端输入：
// 它像查询的其余部分一样，在进入过滤器之前被解码和校验。
const cursor = z
  .base64url()
  .max(200)
  .transform((value, ctx) => {
    try {
      return JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;
    } catch {
      ctx.addIssue({ code: 'custom', message: 'Invalid cursor' });
      return z.NEVER;
    }
  })
  // 排序值（价格，或毫秒级的创建时间）以及本页最后一个商品的 _id。
  // 有边界：1e300 是数字，但不是 MongoDB 能比较的日期。
  .pipe(z.tuple([z.number().int().min(0).max(8.64e15), objectId]));

// 严格模式：未知或拼错的参数会得到 400，而不是一个未过滤的列表。
export const listProductsQuerySchema = z.strictObject({
  category: category.optional(),
  minPrice: z.coerce.number().int().min(0).optional(),
  maxPrice: z.coerce.number().int().min(0).optional(),
  inStock: z.stringbool().optional(),
  // 只允许有索引的排序：参见 schema。
  sort: z.enum(['-createdAt', 'price', '-price']).default('-createdAt'),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  cursor: cursor.optional(),
});
export type ListProductsQuery = z.infer<typeof listProductsQuerySchema>;
```

列表用 **游标** 分页，而不是用 `page` 和 `skip()`。`skip(n)` 要走过 `n` 个商品之后才返回结果，因此越深的页越慢；而且当有人在读第 1 页时新建了一个商品，后面的每一页都会错位，于是第 2 页会重复一个商品。游标指明本页的最后一个商品，下一页从它之后开始。客户端把每页的 `nextCursor` 作为 `cursor` 传回，遇到 `null` 时停止。

- **排序是白名单。** 每种允许的排序在其字段上都有索引，过滤列表还额外有以 `category` 打头的索引，因此无论页有多深，MongoDB 都只读取一页索引项。对任何其他字段排序，都要先读取并排序所有匹配的商品，然后才返回第一个。要新增一种排序，先为它添加索引。
- **每种排序都以 `_id` 结尾。** 许多商品价格相同，没有决胜字段时它们的顺序是不确定的，于是某页可能重复或跳过商品。`_id` 唯一，因此价格与 `_id` 合起来构成全序，游标同时保存两者。
- **游标是客户端输入。** 它是 base64url 编码的 JSON，没有任何机制阻止客户端发送自己构造的游标。schema 会解码并校验它，所以一个在本该是价格的位置放了操作符对象的伪造游标会得到 400。
- **查询 schema 是严格的。** `z.strictObject()` 会拒绝它未声明的参数，因此拼错的 `?catgory=mice` 会得到 400，而不是一个未过滤的目录。Node 适配器的查询解析器会把 `?category[$ne]=x` 保留为名为 `category[$ne]` 的参数，同样会被拒绝；如果换成会构建嵌套对象的解析器，比如 `qs`，它就会是一个对象，而字符串 schema 会拒绝它。

服务的 `list()` 把查询转换为过滤器和排序：

```typescript
@@filename(src/products/products.service)
import type { Model, QueryFilter } from 'mongoose';
import { Product, type ProductDocument } from './product.schema.js';
import type { CreateProductDto, ListProductsQuery, UpdateProductDto } from './products.schemas.js';

export interface ProductPage {
  items: ProductDocument[];
  /** 把它作为 `cursor` 传回以获取下一页；最后一页为 `null`。 */
  nextCursor: string | null;
}

// 每种排序最后都按 _id 排序，这样价格相同的商品也能保持固定顺序。
const sorts = {
  '-createdAt': { field: 'createdAt', direction: -1 },
  price: { field: 'price', direction: 1 },
  '-price': { field: 'price', direction: -1 },
} as const satisfies Record<ListProductsQuery['sort'], unknown>;

@Injectable()
export class ProductsService implements OnModuleInit {
  // ...

  async list({ category, minPrice, maxPrice, inStock, sort, limit, cursor }: ListProductsQuery): Promise<ProductPage> {
    const { field, direction } = sorts[sort];
    // 逐字段地用经过校验的值构建：从不把请求对象展开进过滤器。
    const filter: QueryFilter<Product> = {};
    if (category !== undefined) {
      filter.category = category;
    }
    if (minPrice !== undefined || maxPrice !== undefined) {
      filter.price = { $gte: minPrice ?? 0, $lte: maxPrice ?? Number.MAX_SAFE_INTEGER };
    }
    if (inStock !== undefined) {
      filter.stock = inStock ? { $gt: 0 } : 0;
    }
    if (cursor) {
      // 按排序顺序位于游标之后的商品：排序值更大，或者排序值相同而 _id 更大。
      const [lastValue, lastId] = cursor;
      const value = field === 'createdAt' ? new Date(lastValue) : lastValue;
      const after = direction === 1 ? '$gt' : '$lt';
      filter.$and = [
        { [field]: { [direction === 1 ? '$gte' : '$lte']: value } },
        { $or: [{ [field]: { [after]: value } }, { _id: { [after]: lastId } }] },
      ];
    }

    // 多取一个：如果它被返回，说明还有下一页。
    const found = await this.productModel
      .find(filter)
      .sort({ [field]: direction, _id: direction })
      .limit(limit + 1);
    const items = found.slice(0, limit);
    const last = items.at(-1);
    const nextCursor =
      found.length > limit && last
        ? Buffer.from(JSON.stringify([+last[field], last.id])).toString('base64url')
        : null;
    return { items, nextCursor };
  }
}
```

对于 `sort=-price`，游标的条件读作「价格更低，或者价格相同而 `_id` 更小」。价格外层那个 `$lte` 让 MongoDB 能从游标处开始扫描索引。对 `?category=mice&sort=-price&limit=5` 的靠后一页执行 `explain()`，会看到 `category_1_price_1__id_1` 索引、没有 `SORT` 阶段，并且只检查了 6 个文档：本页的文档，加上告诉 `list()` 还有下一页的那一个额外商品。

控制器把这五个路由映射到服务，并在参数上挂载 schema：

```typescript
@@filename(src/products/products.controller)
import { Body, Controller, Delete, Get, HttpCode, Param, Patch, Post, Query } from '@nestjs/common';
import {
  createProductSchema,
  listProductsQuerySchema,
  objectId,
  updateProductSchema,
  type CreateProductDto,
  type ListProductsQuery,
  type UpdateProductDto,
} from './products.schemas.js';
import { ProductsService } from './products.service.js';

const productId = { schema: objectId };

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Get()
  list(@Query({ schema: listProductsQuerySchema }) query: ListProductsQuery) {
    return this.productsService.list(query);
  }

  @Get(':id')
  findOne(@Param('id', productId) id: string) {
    return this.productsService.findOne(id);
  }

  @Post()
  create(@Body({ schema: createProductSchema }) dto: CreateProductDto) {
    return this.productsService.create(dto);
  }

  @Patch(':id')
  update(@Param('id', productId) id: string, @Body({ schema: updateProductSchema }) dto: UpdateProductDto) {
    return this.productsService.update(id, dto);
  }

  @Delete(':id')
  @HttpCode(204)
  remove(@Param('id', productId) id: string) {
    return this.productsService.remove(id);
  }
}
```

`POST` 默认返回 `201 Created`，而 `DELETE` 设置为 `204 No Content`，因为没有什么可返回。商品模块注册模型、控制器和服务：

```typescript
@@filename(src/products/products.module)
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Product, ProductSchema } from './product.schema.js';
import { ProductsController } from './products.controller.js';
import { ProductsService } from './products.service.js';

@Module({
  imports: [MongooseModule.forFeature([{ name: Product.name, schema: ProductSchema }])],
  controllers: [ProductsController],
  providers: [ProductsService],
})
export class ProductsModule {}
```

`MongooseModule.forFeature()` 在根模块中由 `MongooseModule.forRootAsync()` 打开的连接上注册模型，并让它可以通过 `@InjectModel(Product.name)` 注入。

#### 重复键返回 409

当插入或更新会让两个商品拥有同一个 SKU 时，MongoDB 会以一个 `code` 为 `11000` 的 `MongoServerError` 拒绝它。Nest 不认识这个错误，所以客户端得到 500，其中没有任何可据以行动的信息。这其实是与现有数据的冲突，应当返回 409，而一个 [异常过滤器](/exception-filters#inheritance) 可以一次性为所有集合说明这一点：

```typescript
@@filename(src/common/duplicate-key.filter)
import { ConflictException, Catch, type ArgumentsHost } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { mongo } from 'mongoose';

const DUPLICATE_KEY = 11000;

/** 唯一索引拒绝了这次写入：返回点明字段的 409，而不是 500。 */
@Catch(mongo.MongoServerError)
export class DuplicateKeyFilter extends BaseExceptionFilter {
  catch(error: mongo.MongoServerError, host: ArgumentsHost) {
    if (error.code !== DUPLICATE_KEY) {
      // 其他任何数据库错误仍然是 500，并按 500 记录日志。
      return super.catch(error, host);
    }
    // keyValue 保存索引拒绝的那些值，例如 { sku: 'KB-001' }。
    const fields = Object.keys(error.keyValue ?? {});
    const message = `This ${fields.join(', ') || 'key'} is already taken`;
    super.catch(new ConflictException(message, { errorCode: 'DUPLICATE_KEY' }), host);
  }
}
```

- **它捕获的是 Mongoose 自带驱动副本的 `MongoServerError`**，即从 `mongoose` 导入的 `mongo`，所以这个类就是 Mongoose 抛出的那个类。
- **其他所有服务器错误都交给 `BaseExceptionFilter`**，它返回 500 并记录日志，与没有过滤器时一样。一个对来自 MongoDB 的任何错误都返回 409 的过滤器会掩盖真正的故障。
- **消息指明字段，而不指明值**，尽管 `keyValue` 也保存了值：一个回显值的消息，总有一天会回显不该回显的值。

根模块在后面的小节中用 `APP_FILTER` 注册它。

> info **提示** 插入之前的检查，例如「这个 SKU 被占用了吗？」，并不能替代索引。两个请求可以在对方插入之前都通过检查，然后两次插入都成功。文末的测试会同时发送十个使用相同 SKU 的创建请求：索引只放行一个。

#### 添加健康检查

容器平台会问两个问题：进程是否存活，以及它现在能否处理请求。[`@nestjs/terminus`](/reliability/terminus) 回答这两个问题，并且带有针对 Mongoose 的指示器，它会 ping `@nestjs/mongoose` 打开的连接（参见 [其他数据库指示器](/reliability/terminus#other-database-indicators)）：

```typescript
@@filename(src/health/health.controller)
import { Controller, Get } from '@nestjs/common';
import { HealthCheck, HealthCheckService, MongooseHealthIndicator } from '@nestjs/terminus';

@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly mongoose: MongooseHealthIndicator,
  ) {}

  @Get('live')
  @HealthCheck()
  live() {
    return this.health.check([]);
  }

  @Get('ready')
  @HealthCheck()
  ready() {
    return this.health.check([() => this.mongoose.pingCheck('mongodb').withTimeout('1s')]);
  }
}
```

健康模块导入 Terminus，它提供 `HealthCheckService` 和 `MongooseHealthIndicator`：

```typescript
@@filename(src/health/health.module)
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller.js';

@Module({
  imports: [TerminusModule],
  controllers: [HealthController],
})
export class HealthModule {}
```

存活检查不看数据库：重启也修不好它。就绪检查在 MongoDB 一秒内没有响应 ping 时失败，平台会停止向该实例发送流量，直到它再次通过。

#### 组装应用

根模块用配置中的 URI 打开连接，并为每个路由注册校验管道和过滤器：

```typescript
@@filename(src/app.module)
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_FILTER, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { createObserveModule } from '@nestjs/observe';
import { DuplicateKeyFilter } from './common/duplicate-key.filter.js';
import { envSchema, type Env } from './config.js';
import { HealthModule } from './health/health.module.js';
import { ProductsModule } from './products/products.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // 放在最前，这样它最后关闭，还能把其他模块做过的事情发送出去。
    ObserveModule.forRoot({
      // 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前为空：此时 SDK 不发送任何内容。
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'products-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    MongooseModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        uri: config.get('MONGODB_URI', { infer: true }),
        // 查询在失败前等待可连接服务器的时间（驱动默认是 30s）。
        serverSelectionTimeoutMS: 5_000,
        // 在启动时构建 schema 的索引。生产环境改由发布步骤构建。
        autoIndex: config.get('NODE_ENV', { infer: true }) !== 'production',
        // 每个模型在被注入之前都等待自己的集合和索引就绪。
        waitForModelInit: true,
      }),
    }),
    ProductsModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_FILTER, useClass: DuplicateKeyFilter },
  ],
})
export class AppModule {}
```

- **`forRootAsync()`** 在 `ConfigModule` 校验之后从 `ConfigService` 读取 URI，并在应用关闭时关闭连接（参见 [异步配置](/data/mongodb#async-configuration)）。
- **`serverSelectionTimeoutMS`** 是一次操作等待可连接的 MongoDB 服务器的时间。若用驱动默认的 30 秒，故障期间的一个请求要挂起那么久才得到 500；用 5 秒，它在 5 秒后就得到 500。
- **`autoIndex`** 除生产环境外都开启；在生产环境中由 [发布步骤](/tutorials/mongodb-crud-api#create-indexes-in-production) 构建索引。
- **`waitForModelInit`** 让每个模型在被注入之前等待 `model.init()`，它会创建集合并构建索引。没有它，Mongoose 在后台构建索引：应用可能在 `sku` 上的唯一索引还不存在时就开始处理请求；而且如果集合中已经有重复的 SKU，构建会失败却不留一行日志，此后应用就一直接受重复项。有了它，构建失败会带着 MongoDB 的错误中止启动。它需要 `@nestjs/mongoose` 12.0.2 或更高版本（参见 [等待索引](/data/mongodb#wait-for-indexes)）。
- **管道和过滤器是 `AppModule` 的提供者**，而不是 `main.ts` 中的调用，这样那些不经过 `main.ts`、直接引导 `AppModule` 的测试也能拿到它们。
- **`ObserveModule` 在 `imports` 中最靠前**，与 [SDK 的快速开始](/observability/sdk#quick-start) 一致：模块按相反顺序关闭，所以它最后停止，并把其他模块记录的内容发送出去（参见 [关闭](/observability/sdk#shutdown)）。`createObserveModule()` 返回它以及 `ObserveInstrument`，后者由 `main.ts` 传给 Nest。
- **在你链接项目之前，密钥对是空的。** 没有密钥对时，SDK 不发送任何内容，并在启动时说明这一点。`npx @nestjs/observe link` 会把 `OBSERVE_APP_KEY` 和 `OBSERVE_APP_SECRET` 写入 `.env`，并把 `--env-file .env` 加入 `start` 脚本，这样在导入 `AppModule`（也就是 SDK 读取它们）之前，它们就已经在环境变量里了（参见 [从终端链接](/observability/sdk#linking-from-the-terminal)）。

`main.ts` 在 Node 适配器上创建应用，并加入任何 API 边缘都需要的东西。使用适配器时，应用选项（其中包括 `instrument`）是第三个参数：

```typescript
@@filename(src/main)
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  // 生产环境每行一个 JSON 对象；开发环境是可读的文本。
  logger: new ConsoleLogger({ json: production }),
});
app.useSecurityHeaders();
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });

const document = new DocumentBuilder().setTitle('Products API').setVersion('1.0').build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));

await app.listen(config.get('PORT', { infer: true }));
```

- **生产环境写 JSON 日志。** 当 `NODE_ENV` 为 `production` 时，`ConsoleLogger` 每行写一个 JSON 对象，否则写可读文本（参见 [JSON 日志](/application/logger#json-logging)）。它在 `ConfigModule` 读取 `.env` 之前创建，因此它从进程环境中读取 `NODE_ENV`，也就是你的平台设置它的地方。
- **安全响应头。** `app.useSecurityHeaders()` 在每个响应上发送 [Helmet](https://helmetjs.github.io/) 会以其默认值发送的那些响应头，错误响应也包括在内（参见 [安全响应头](/security/helmet)）。
- **关闭钩子。** `enableShutdownHooks()` 让应用在收到 `SIGTERM` 时关闭，容器平台每次部署都会发送这个信号：服务器停止接受连接，`@nestjs/mongoose` 关闭 MongoDB 连接。
- **CORS 来自配置。** 除非 `CORS_ORIGINS` 中列出某个浏览器来源，否则不允许它。不带 `origin` 调用 `enableCors()` 时，它会对每个网站返回 `Access-Control-Allow-Origin: *`（参见 [默认允许的来源](/security/cors#default-allowed-origins)）。
- **OpenAPI 文档。** [`@nestjs/swagger`](/openapi/introduction) 从控制器构建它，并从校验这些参数的同一批 Zod schema 中取得请求体、查询参数和路由参数（参见 [Standard Schema](/openapi/introduction#standard-schema-zod-valibot)）。Swagger UI 位于 `http://localhost:3000/docs`，文档位于 `http://localhost:3000/docs-json`。

OpenAPI 文档中的 id 参数，来自 `objectId`：

```json
{
  "name": "id",
  "required": true,
  "in": "path",
  "schema": {
    "type": "string",
    "pattern": "^[0-9a-f]{24}$"
  }
}
```

#### 试一试

启动应用：

```bash
$ npm run start
```

创建一个商品。响应中有 `id` 和 `version`，没有 `_id` 或 `__v`：

```bash
$ curl localhost:3000/products --json '{"sku":"kb-001","name":"Mechanical keyboard","description":"Hot-swappable switches","category":"Keyboards","price":12900,"stock":5}'
{"sku":"KB-001","name":"Mechanical keyboard","description":"Hot-swappable switches","category":"keyboards","price":12900,"stock":5,"version":1,"createdAt":"2026-11-23T18:54:18.607Z","updatedAt":"2026-11-23T18:54:18.607Z","id":"6b048bda3718dc2b670713ac"}
```

小写的同一个 SKU 仍是同一个 SKU，唯一索引会拒绝它。一个对象形式的值（操作符注入就会这样发送）永远到不了 MongoDB：

```bash
$ curl localhost:3000/products --json '{"sku":"KB-001","name":"Compact keyboard","category":"keyboards","price":8900,"stock":3}'
{"message":"This sku is already taken","error":"Conflict","statusCode":409,"errorCode":"DUPLICATE_KEY"}
$ curl localhost:3000/products --json '{"sku":"KB-002","name":{"$gt":""},"category":"keyboards","price":8900,"stock":3}'
{"message":["name: Invalid input: expected string, received object"],"error":"Bad Request","statusCode":400}
```

格式错误的 id 是客户端的错误，而格式正确却匹配不到任何东西的 id 是商品缺失：

```bash
$ curl localhost:3000/products/not-an-id
{"message":["Invalid ObjectId"],"error":"Bad Request","statusCode":400}
$ curl localhost:3000/products/507f1f77bcf86cd799439011
{"message":"Product not found","error":"Not Found","statusCode":404}
```

从版本 1 修改价格。一个没看到第一次修改的客户端再次以版本 1 发起修改会被拒绝，版本号是操作符的请求同样被拒绝：

```bash
$ curl -X PATCH localhost:3000/products/6b048bda3718dc2b670713ac --json '{"price":13900,"version":1}'
{"sku":"KB-001","name":"Mechanical keyboard","description":"Hot-swappable switches","category":"keyboards","price":13900,"stock":5,"version":2,"createdAt":"2026-11-23T18:54:18.607Z","updatedAt":"2026-11-23T18:54:29.338Z","id":"6b048bda3718dc2b670713ac"}
$ curl -X PATCH localhost:3000/products/6b048bda3718dc2b670713ac --json '{"stock":4,"version":1}'
{"message":"Product has changed since version 1","error":"Conflict","statusCode":409,"errorCode":"VERSION_CONFLICT"}
$ curl -X PATCH localhost:3000/products/6b048bda3718dc2b670713ac --json '{"stock":4,"version":{"$gte":0}}'
{"message":["version: Invalid input: expected number, received object"],"error":"Bad Request","statusCode":400}
```

用同样的方式添加四只鼠标，其中两只价格相同，然后按价格每次两只地翻页。第二页从游标之后开始，游标保存着最后一个商品的价格和 `_id`。过滤器可以组合，而 schema 未声明的排序或参数会得到 400（`-g` 让 curl 不把方括号当作模式）：

```bash
$ curl 'localhost:3000/products?category=mice&sort=price&limit=2'
{"items":[{"sku":"MS-001","name":"Wired mouse",...,"price":1900,"stock":12,...,"id":"6b048bef3718dc2b670713ae"},{"sku":"MS-002","name":"Wireless mouse",...,"price":2900,"stock":0,...,"id":"6b048bef3718dc2b670713af"}],"nextCursor":"WzI5MDAsIjZiMDQ4YmVmMzcxOGRjMmI2NzA3MTNhZiJd"}
$ curl 'localhost:3000/products?category=mice&sort=price&limit=2&cursor=WzI5MDAsIjZiMDQ4YmVmMzcxOGRjMmI2NzA3MTNhZiJd'
{"items":[{"sku":"MS-003","name":"Vertical mouse",...,"price":2900,"stock":4,...,"id":"6b048bef3718dc2b670713b0"},{"sku":"MS-004","name":"Trackball",...,"price":4900,"stock":2,...,"id":"6b048bfc3718dc2b670713b1"}],"nextCursor":null}
$ curl 'localhost:3000/products?category=mice&inStock=true&maxPrice=3000'
{"items":[{"sku":"MS-003","name":"Vertical mouse",...,"price":2900,"stock":4,...},{"sku":"MS-001","name":"Wired mouse",...,"price":1900,"stock":12,...}],"nextCursor":null}
$ curl 'localhost:3000/products?sort=stock'
{"message":["sort: Invalid option: expected one of \"-createdAt\"|\"price\"|\"-price\""],"error":"Bad Request","statusCode":400}
$ curl -g 'localhost:3000/products?category[$ne]=mice'
{"message":["Unrecognized key: \"category[$ne]\""],"error":"Bad Request","statusCode":400}
```

删除这个商品。第二次删除什么都找不到：

```bash
$ curl -i -X DELETE localhost:3000/products/6b048bda3718dc2b670713ac
HTTP/1.1 204 No Content
...
$ curl -X DELETE localhost:3000/products/6b048bda3718dc2b670713ac
{"message":"Product not found","error":"Not Found","statusCode":404}
```

当 MongoDB 停止响应时，就绪检查会在一秒超时内失败，而存活检查仍然通过：

```bash
$ curl localhost:3000/health/ready
{"status":"ok","info":{"mongodb":{"responseTime":5,"status":"up"}},"error":{},"details":{"mongodb":{"responseTime":5,"status":"up"}}}
$ docker pause catalog-db
$ curl -i localhost:3000/health/ready
HTTP/1.1 503 Service Unavailable
...
{"status":"error","info":{},"error":{"mongodb":{"message":"timeout of 1000ms exceeded","responseTime":1001,"status":"down"}},"details":{"mongodb":{"message":"timeout of 1000ms exceeded","responseTime":1001,"status":"down"}}}
$ curl localhost:3000/health/live
{"status":"ok","info":{},"error":{},"details":{}}
$ docker unpause catalog-db
```

#### 测试它

这里重要的保证都与并发有关，所以测试针对真实的 MongoDB 服务器运行，并用 Node 适配器提供的 `app.inject()` 发送并发请求，这样就不需要有服务器在监听。测试引导真实的 `AppModule`，只改一处：把连接替换为指向测试文件自有数据库的连接，`createTestApp()` 会先清空它：

```typescript
@@filename(test/test-app)
import { getConnectionToken } from '@nestjs/mongoose';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { createConnection } from 'mongoose';
import { AppModule } from '../src/app.module.js';

/**
 * 真实的 AppModule，运行在它自己的数据库上：`<TEST_MONGODB_URI 中的数据库名>_<name>`，
 * 先清空。每个测试文件传入自己的名字，因此各文件可以并行运行。
 */
export async function createTestApp(name: string): Promise<NestNodeApplication> {
  const server = await createConnection(process.env.TEST_MONGODB_URI!).asPromise();
  const connection = server.useDb(`${server.name}_${name}`);
  await connection.dropDatabase();

  const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
    .overrideProvider(getConnectionToken())
    .useValue(connection)
    .compile();
  const app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
  // 关闭应用也会关闭连接。
  return app.init();
}
```

`useDb()` 共享第一个连接的连接池，关闭应用会同时关闭两者。由于每个文件都有自己的数据库，Vitest 可以并行运行这些文件。测试配置为应用提供它在启动时校验的环境变量；该 URI 从不被使用：

```typescript
@@filename(vitest.config.e2e)
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      // 在启动时校验；测试会用它们自己的连接替换掉这个连接。
      MONGODB_URI: 'mongodb://unused-in-tests',
    },
  },
});
```

第一个文件覆盖 CRUD 路由以及它们拒绝的请求：

```typescript
@@filename(test/products.e2e-spec)
import type { NestNodeApplication } from '@nestjs/platform-node';
import { createTestApp } from './test-app.js';

const url = process.env.TEST_MONGODB_URI;

describe.skipIf(!url)('Products API (e2e)', () => {
  let app: NestNodeApplication;

  beforeAll(async () => {
    app = await createTestApp('products');
  });
  afterAll(() => app.close());

  const keyboard = {
    sku: 'kb-001',
    name: 'Mechanical keyboard',
    description: 'Hot-swappable switches',
    category: 'Keyboards',
    price: 12900,
    stock: 5,
  };

  async function create(payload: object) {
    const res = await app.inject({ method: 'POST', url: '/products', payload });
    expect(res.statusCode).toBe(201);
    return res.json<{ id: string; version: number }>();
  }

  it('creates, reads, updates and deletes a product, with `id` and no `_id` or `__v`', async () => {
    const created = await create(keyboard);
    expect(created).toMatchObject({ sku: 'KB-001', category: 'keyboards', version: 1 });
    expect(created).not.toHaveProperty('_id');
    expect(created).not.toHaveProperty('__v');

    const found = await app.inject({ method: 'GET', url: `/products/${created.id}` });
    expect(found.json()).toEqual(created);

    const updated = await app.inject({
      method: 'PATCH',
      url: `/products/${created.id}`,
      payload: { price: 13900, version: 1 },
    });
    expect(updated.statusCode).toBe(200);
    // 只有价格变了：客户端没有发送的字段保持不变。
    expect(updated.json()).toMatchObject({ ...created, price: 13900, version: 2, updatedAt: expect.any(String) });

    expect((await app.inject({ method: 'DELETE', url: `/products/${created.id}` })).statusCode).toBe(204);
    expect((await app.inject({ method: 'GET', url: `/products/${created.id}` })).statusCode).toBe(404);
  });

  it('answers 400 for a malformed id and 404 for an unknown one', async () => {
    for (const method of ['GET', 'PATCH', 'DELETE'] as const) {
      const res = await app.inject({ method, url: '/products/not-an-id', payload: { stock: 1, version: 1 } });
      expect(res.statusCode).toBe(400);
    }
    const unknown = await app.inject({ method: 'GET', url: '/products/507f1f77bcf86cd799439011' });
    expect(unknown.statusCode).toBe(404);
    const unknownUpdate = await app.inject({
      method: 'PATCH',
      url: '/products/507f1f77bcf86cd799439011',
      payload: { stock: 1, version: 1 },
    });
    expect(unknownUpdate.statusCode).toBe(404);
  });

  it('answers 409 for a duplicate SKU, in any letter case, on create and on update', async () => {
    await create({ ...keyboard, sku: 'MS-001', name: 'Mouse' });
    const duplicate = await app.inject({ method: 'POST', url: '/products', payload: { ...keyboard, sku: 'ms-001' } });
    expect(duplicate.statusCode).toBe(409);
    expect(duplicate.json()).toMatchObject({ errorCode: 'DUPLICATE_KEY' });

    const other = await create({ ...keyboard, sku: 'MS-002', name: 'Mouse 2' });
    const renamed = await app.inject({
      method: 'PATCH',
      url: `/products/${other.id}`,
      payload: { sku: 'MS-001', version: other.version },
    });
    expect(renamed.statusCode).toBe(409);
  });

  it('refuses query operators wherever a value is expected', async () => {
    const { id } = await create({ ...keyboard, sku: 'OP-001' });
    const attempts = [
      { method: 'POST', url: '/products', payload: { ...keyboard, sku: 'OP-002', name: { $gt: '' } } },
      // 版本号是 { $gte: 0 } 会匹配任意版本，从而绕过过期写入检查。
      { method: 'PATCH', url: `/products/${id}`, payload: { stock: 0, version: { $gte: 0 } } },
      { method: 'GET', url: '/products?category[$ne]=keyboards' },
      { method: 'GET', url: '/products?category=a&category=b' },
      { method: 'GET', url: `/products?cursor=${encode([{ $gt: 0 }, id])}` },
      { method: 'GET', url: `/products?cursor=${encode([1e300, id])}` },
      { method: 'GET', url: '/products?sort=stock' },
    ] as const;
    for (const attempt of attempts) {
      expect((await app.inject(attempt)).statusCode).toBe(400);
    }
    const product = await app.inject({ method: 'GET', url: `/products/${id}` });
    expect(product.json()).toMatchObject({ name: 'Mechanical keyboard', stock: 5, version: 1 });
  });

  it('refuses an update with nothing to update, or with a null field', async () => {
    const { id } = await create({ ...keyboard, sku: 'NU-001' });
    for (const payload of [{ version: 1 }, { name: null, version: 1 }, { price: 19.99, version: 1 }]) {
      expect((await app.inject({ method: 'PATCH', url: `/products/${id}`, payload })).statusCode).toBe(400);
    }
  });

  it('pages through a filtered list in every sort, without repeating or skipping a product', async () => {
    // 十二只鼠标，四种价格：这些并列顺序只有 _id 决胜字段才能确定。
    const ids = new Set<string>();
    for (let i = 0; i < 12; i++) {
      const { id } = await create({ sku: `PG-${i}`, name: `Mouse ${i}`, category: 'mice', price: 1000 + (i % 4) * 500, stock: i % 3 });
      ids.add(id);
    }

    type Item = { id: string; price: number; createdAt: string };
    for (const [sort, key, sign] of [['-createdAt', 'createdAt', -1], ['price', 'price', 1], ['-price', 'price', -1]] as const) {
      const seen: Item[] = [];
      let cursor: string | null = null;
      do {
        const res = await app.inject({
          method: 'GET',
          url: `/products?category=mice&sort=${sort}&limit=5${cursor ? `&cursor=${cursor}` : ''}`,
        });
        expect(res.statusCode).toBe(200);
        const page: { items: Item[]; nextCursor: string | null } = res.json();
        seen.push(...page.items);
        cursor = page.nextCursor;
      } while (cursor);

      expect(seen.map((p) => p.id).sort()).toEqual([...ids].sort());
      expect(seen.every((p) => !('_id' in p))).toBe(true);
      const values = seen.map((p) => (key === 'price' ? p.price : Date.parse(p.createdAt)));
      expect(values).toEqual([...values].sort((a, b) => sign * (a - b)));
    }

    const inStock = await app.inject({ method: 'GET', url: '/products?category=mice&inStock=true&maxPrice=1500' });
    const items = inStock.json<{ items: { price: number; stock: number }[] }>().items;
    expect(items.length).toBeGreaterThan(0);
    expect(items.every((p) => p.stock > 0 && p.price <= 1500)).toBe(true);
  });
});

function encode(value: unknown) {
  return Buffer.from(JSON.stringify(value)).toString('base64url');
}
```

第二个文件发送并发写入。基于同一版本的十个更新必须恰好产生一次修改，使用同一 SKU 的十次创建必须恰好产生一个商品：

```typescript
@@filename(test/concurrency.e2e-spec)
import type { NestNodeApplication } from '@nestjs/platform-node';
import { createTestApp } from './test-app.js';

const url = process.env.TEST_MONGODB_URI;

describe.skipIf(!url)('Concurrent writes (e2e)', () => {
  let app: NestNodeApplication;

  beforeAll(async () => {
    app = await createTestApp('concurrency');
  });
  afterAll(() => app.close());

  it('applies one of ten concurrent updates of the same version, and refuses the rest', async () => {
    const created = await app.inject({
      method: 'POST',
      url: '/products',
      payload: { sku: 'RACE-1', name: 'Desk mat', category: 'desk', price: 2500, stock: 10 },
    });
    const { id } = created.json<{ id: string }>();

    // 十个客户端读到版本 1，各自设置自己的库存值。
    const results = await Promise.all(
      Array.from({ length: 10 }, (_, i) =>
        app.inject({ method: 'PATCH', url: `/products/${id}`, payload: { stock: i, version: 1 } }),
      ),
    );

    const statuses = results.map((res) => res.statusCode);
    expect(statuses.sort()).toEqual([200, ...Array(9).fill(409)]);
    const winner = results.find((res) => res.statusCode === 200)!.json<{ stock: number }>();
    const product = (await app.inject({ method: 'GET', url: `/products/${id}` })).json();
    expect(product).toMatchObject({ version: 2, stock: winner.stock });
  });

  it('creates one of ten concurrent products with the same SKU', async () => {
    const results = await Promise.all(
      Array.from({ length: 10 }, (_, i) =>
        app.inject({
          method: 'POST',
          url: '/products',
          payload: { sku: 'race-2', name: `Lamp ${i}`, category: 'desk', price: 4900, stock: 1 },
        }),
      ),
    );
    expect(results.map((res) => res.statusCode).sort()).toEqual([201, ...Array(9).fill(409)]);
  });
});
```

在 `package.json` 中添加一个脚本：

```json
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
```

针对 MongoDB 容器运行这两个文件。它们的数据库名以 URI 中的数据库名命名，这里是 `catalog_test_products` 和 `catalog_test_concurrency`：

```bash
$ TEST_MONGODB_URI=mongodb://localhost:27017/catalog_test npm run test:e2e

 Test Files  2 passed (2)
      Tests  8 passed (8)
```

把 `update()` 中 `findOneAndUpdate()` 的过滤器里的 `version` 去掉，第一个并发测试就会失败：十个更新全部成功，每个都覆盖前一个。把 `list()` 中游标条件里的 `_id` 去掉，分页测试就会失败：位于页边界、价格相同的商品会被跳过。从 `AppModule` 中移除 `waitForModelInit`，`onModuleInit()` 就可能在 Mongoose 仍在构建索引时去检查它们：应用会拒绝启动，两个文件都在第一个测试之前就失败。

#### 在生产环境创建索引

构建索引要读取整个集合，并且在运行期间拖慢其他所有请求。Mongoose 的文档因此建议在生产环境关闭 `autoIndex`，`AppModule` 在 `NODE_ENV` 为 `production` 时正是这样做的。改由发布步骤构建索引，每次发布一次，在新版本启动之前完成：

```typescript
@@filename(src/create-indexes)
import { createConnection } from 'mongoose';
import { envSchema } from './config.js';
import { Product, ProductSchema } from './products/product.schema.js';

// 一个发布步骤：在新版本启动之前，构建 schema 所声明的索引。
const { MONGODB_URI } = envSchema.parse(process.env);
const connection = await createConnection(MONGODB_URI, { autoIndex: false }).asPromise();
try {
  // 创建缺失的索引，其他什么都不改：与 syncIndexes() 不同，它从不删除索引。
  await connection.model(Product.name, ProductSchema).createIndexes();
  console.log('Indexes of products:', (await connection.collection('products').indexes()).map((index) => index.name));
} finally {
  await connection.close();
}
```

这是一个普通的 Mongoose 脚本，因为 `AppModule` 在没有它所要创建的那些索引时会拒绝启动。`createIndexes()` 添加缺失的索引；`syncIndexes()` 还会删除 schema 未声明的索引，包括出于某种原因手工添加的索引。

在 `package.json` 中添加一个脚本。`--env-file-if-exists`（Node.js 22.9 或更高版本）在开发环境读取 `.env`，在平台设置环境变量的地方则什么都不做：

```json
"db:indexes": "node --env-file-if-exists=.env dist/create-indexes.js"
```

在发布步骤之前启动生产环境会拒绝运行，而不是在没有唯一索引的情况下接受重复的 SKU（堆栈跟踪已缩短）：

```bash
$ npm run build
$ NODE_ENV=production npm run start:prod
...
Error: Missing indexes on products: [{"sku":1},{"createdAt":-1,"_id":-1},{"price":1,"_id":1},{"category":1,"createdAt":-1,"_id":-1},{"category":1,"price":1,"_id":1}]. Run npm run db:indexes.
```

完成发布步骤后，它就能启动，并以 JSON 格式记录日志：

```bash
$ npm run db:indexes
Indexes of products: [
  '_id_',
  'sku_1',
  'createdAt_-1__id_-1',
  'price_1__id_1',
  'category_1_createdAt_-1__id_-1',
  'category_1_price_1__id_1'
]
$ NODE_ENV=production npm run start:prod
...
{"level":"log","pid":2641,"timestamp":1795460206229,"message":"Nest application successfully started","context":"NestApplication"}
```

#### 生产环境检查清单

- **把 `NODE_ENV` 设为 `production`**，并在新版本启动之前，把 `npm run build` 和 `npm run db:indexes` 作为发布步骤运行。在大集合上新增索引需要一段时间构建：请先单独发布一次来添加它，再发布需要它的查询。
- **把 MongoDB 作为副本集运行**，就像任何托管 MongoDB 服务那样。单台服务器是单点故障，而多文档事务（该 API 并不需要）要求副本集。托管服务的 `mongodb+srv://` URI 能通过配置的校验。
- **创建应用的数据库用户，只让它在应用自己的数据库上拥有 `readWrite` 角色**，并把凭据放进平台的密钥存储，在运行时以 `MONGODB_URI` 注入，而不是写进镜像或提交到仓库的 `.env` 文件。
- **把 `CORS_ORIGINS` 设为你的 Web 应用来源**，带上协议、不带路径；如果没有浏览器调用该 API，就留空。
- **把平台的探针指向健康检查**：存活检查用 `/health/live`，就绪检查用 `/health/ready`。如果启动时 MongoDB 不可达，`@nestjs/mongoose` 会重试九次，每次间隔三秒，每次尝试都等待 `serverSelectionTimeoutMS`，进程会在启动约 70 秒后带着错误退出。
- **用平台的日志驱动从 stdout 收集 JSON 日志。**
- **让每个进入过滤器的值都经过 schema**，在每条新路由、每个游标和每个响应头中都是如此：正是这一点把操作符注入挡在外面。
- **为生产环境准备它自己的 Observe 密钥对**，从项目的 **API Keys** 页面获取，作为 `OBSERVE_APP_KEY` 和 `OBSERVE_APP_SECRET` 放进平台的环境变量：`start:prod` 不加载 `.env`。随后 [NestJS Observe](/observability/overview) 会记录每个请求及其按路由统计的延迟和失败率，以及每个请求的链路（trace），其中包含在对应方法下执行的 MongoDB 查询，查询的值已被移除（参见 [数据库查询与出站 HTTP](/observability/sdk#database-queries-and-outbound-http)）。一个失去索引的列表查询会在用户抱怨之前就表现为慢路由。

#### 接下来做什么

- 让用户使用 JWT 访问令牌和刷新令牌注册并登录，并让每个商品有归属者：[构建带 JWT 认证的 REST API](/tutorials/rest-api-jwt-authentication) 逐步为一个类似的 API 添加登录功能。
- 决定谁可以编辑目录：[授权](/security/authorization)，就像 [电商教程](/tutorials/ecommerce-backend#let-staff-manage-the-catalog) 为员工所做的那样。
- 限制客户端调用 API 的速度：[限流](/security/rate-limiting)。
- 用 schema 而不是 `toJSON` 塑造响应：[基于 schema 的序列化](/application/serialization#schema-based-serialization)。
- Nest 中更多的 Mongoose 用法，从子文档到多数据库：[MongoDB](/data/mongodb)。

