MongoDB 和 Mongoose 可以直接與 Bun 配合使用。本指南假設您已安裝 MongoDB 並將其作為後臺程序/服務在開發機上執行。有關詳細資訊,請遵循此指南。
MongoDB 執行後,建立一個目錄並使用 bun init 初始化它。
mkdir mongoose-appcd mongoose-appbun init然後將 Mongoose 新增為依賴項。
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';
// connect to database
await mongoose.connect('mongodb://127.0.0.1:27017/mongoose-app');
// create new Animal
const cow = new Animal({
name: 'Cow',
sound: 'Moo',
});
await cow.save(); // saves to the database
// read all Animals
const animals = await Animal.find();
animals[0].speak(); // logs "Moo!"
// disconnect
await mongoose.disconnect();
讓我們使用 bun run 來執行它。
bun run index.tsMoo!