使用 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!