使用 Mongoose 和 Bun 读写 MongoDB 数据
MongoDB 和 Mongoose 无需额外配置即可与 Bun 一起使用。本指南假设你已经安装了 MongoDB,并将其作为后台进程或服务运行在开发机器上。详情请参阅 MongoDB 安装指南。
MongoDB 运行后,创建一个目录并用 bun init 初始化。
terminal
mkdir mongoose-app
cd mongoose-app
bun init
然后添加 Mongoose 作为依赖。
terminal
bun add mongoose
在 schema.ts 中声明并导出一个 Animal 模型。
import * as mongoose from "mongoose";
const animalSchema = new mongoose.Schema(
{
name: { 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,并向数据库中添加一些数据。
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({
name: "Cow",
sound: "Moo",
});
await cow.save(); // 保存到数据库
// 读取所有 Animals
const animals = await Animal.find();
animals[0]!.speak(); // logs "Moo!"
// 断开连接
await mongoose.disconnect();
使用 bun run 运行该文件。
terminal
bun run index.ts
Text
Moo!