Documentation Index
Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
Use this file to discover all available pages before exploring further.
MongoDB 和 Mongoose 可以直接与 Bun 一起使用。本指南假设你已经安装并运行了 MongoDB,且它作为后台进程/服务运行在你的开发机器上。详情请参见此指南。
MongoDB 运行后,创建一个目录并用 bun init 初始化。
mkdir mongoose-app
cd mongoose-app
bun init
然后添加 Mongoose 作为依赖。
在 schema.ts 中,我们将声明并导出一个 Animal 模型。
schema.tsimport * 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,并向数据库添加数据。
index.tsimport * 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 运行它。
这是一个使用 TypeScript 和 Bun 配合 Mongoose 的入门示例。在你构建应用的过程中,请参考官方的 MongoDB 和 Mongoose 站点以获取完整文档。