Skip to content

MongoDB 和 Mongoose 可以在 Bun 上开箱即用。本指南假设你已经安装了 MongoDB 并在开发机器上作为后台进程/服务运行它。请按照 本指南 获取详细信息。


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

sh
mkdir mongoose-app
cd mongoose-app
bun init

然后将 Mongoose 添加为依赖项。

sh
bun add mongoose

schema.ts 中,我们将声明并导出一个简单的 Animal 模型。

ts
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
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
bun run index.ts
txt
Moo!

这是使用 TypeScript 和 Bun 使用 Mongoose 的简单介绍。在构建应用时,请参阅官方 MongoDBMongoose 网站获取完整文档。

Bun学习网由www.bunjs.com.cn整理维护