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.tstxt
Moo!這是使用 TypeScript 和 Bun 使用 Mongoose 的簡單介紹。在構建應用時,請參閱官方 MongoDB 和 Mongoose 網站獲取完整文檔。