> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 Mongoose 和 Bun 读写 MongoDB 数据

MongoDB 和 Mongoose 可以在 Bun 中无需额外配置即可工作。本指南假设你已安装 MongoDB 并在开发机器上将其作为后台进程或服务运行。详情请参见 [MongoDB 安装指南](https://www.mongodb.com/docs/manual/installation/)。

***

MongoDB 运行后，创建一个目录并使用 `bun init` 初始化。

```sh terminal icon="terminal" theme={null}
mkdir mongoose-app
cd mongoose-app
bun init
```

***

然后将 Mongoose 添加为依赖。

```sh terminal icon="terminal" theme={null}
bun add mongoose
```

***

在 `schema.ts` 中，声明并导出一个 `Animal` 模型。

```ts schema.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import * as mongoose from "mongoose";

const animalSchema = new mongoose.Schema(
  {
    title: { type: String, required: true },
    sound: { type: String, required: true },
  },
  {
    methods: {
      speak() {
        console.log(`${this.sound}！`);
      },
    },
  },
)；

export type Animal = mongoose.InferSchemaType<typeof animalSchema>;
export const Animal = mongoose.model("Animal", animalSchema);
```

***

在 `index.ts` 中，导入 `Animal`，连接到 MongoDB，并向数据库添加一些数据。

```ts index.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import * as mongoose from "mongoose";
import { Animal } from "./schema";

// 连接到数据库
await mongoose.connect("mongodb://127.0.0.1:27017/mongoose-app");

// 创建新的 Animal
const cow = new Animal({
  title: "Cow",
  sound: "Moo",
});
await cow.save(); // 保存到数据库

// 读取所有 Animals
const animals = await Animal.find();
animals[0].speak(); // 打印 "Moo！"

// 断开连接
await mongoose.disconnect();
```

***

使用 `bun run` 运行该文件。

```bash terminal icon="terminal" theme={null}
bun run index.ts
```

```txt theme={null}
Moo！
```

***

在构建应用时，请参考官方 [MongoDB](https://www.mongodb.com/docs) 和 [Mongoose](https://mongoosejs.com/docs/) 文档。
