Skip to main content
MongoDB 和 Mongoose 可以直接与 Bun 一起使用。本指南假设你已经安装并运行了 MongoDB,且它作为后台进程/服务运行在你的开发机器上。详情请参见此指南
MongoDB 运行后,创建一个目录并用 bun init 初始化。
terminal
mkdir mongoose-app
cd mongoose-app
bun init

然后添加 Mongoose 作为依赖。
terminal
bun add mongoose

schema.ts 中声明并导出一个简单的 Animal 模型。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79schema.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,并向数据库添加数据。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79index.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 运行它。
terminal
bun run index.ts
Moo!

这只是使用 Mongoose、TypeScript 和 Bun 的简单介绍。在构建应用程序时,请参考官方的 MongoDBMongoose 文档获取完整资料。