Skip to content

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 을 import 하고 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(); // 데이터베이스에 저장

// 모든 Animal 읽기
const animals = await Animal.find();
animals[0].speak(); // "Moo!" 로그 출력

// 연결 끊기
await mongoose.disconnect();

bun run 으로 이를 실행해 보겠습니다.

bash
bun run index.ts
txt
Moo!

이는 TypeScript 와 Bun 으로 Mongoose 를 사용하는 간단한 소개입니다. 애플리케이션을 빌드할 때는 완전한 문서를 위해 공식 MongoDBMongoose 사이트를 참조하세요.

Bun by www.bunjs.com.cn 편집