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

# 使用 Mongoose 和 Bun 读写 MongoDB 数据

MongoDB 和 Mongoose 可以直接与 Bun 一起使用。本指南假设你已经安装并运行了 MongoDB，且它作为后台进程/服务运行在你的开发机器上。详情请参见[此指南](https://www.mongodb.com/docs/manual/installation/)。

***

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

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
mkdir mongoose-app
cd mongoose-app
bun init
```

***

然后添加 Mongoose 作为依赖。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun add mongoose
```

***

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

```ts schema.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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={"theme":{"light":"github-light","dark":"dracula"}}
bun run index.ts
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
Moo!
```

***

这是一个使用 TypeScript 和 Bun 配合 Mongoose 的入门示例。在你构建应用的过程中，请参考官方的 [MongoDB](https://www.mongodb.com/docs) 和 [Mongoose](https://mongoosejs.com/docs/) 站点以获取完整文档。
