Read and write data to MongoDB using Mongoose and Bun

MongoDB and Mongoose work with Bun with no extra configuration. This guide assumes you've already installed MongoDB and are running it as a background process or service on your development machine. See the MongoDB installation guide for details.


Once MongoDB is running, create a directory and initialize it with bun init.

terminal
mkdir mongoose-app
cd mongoose-app
bun init

Then add Mongoose as a dependency.

terminal
bun add mongoose

In schema.ts, declare and export an Animal model.

schema.ts
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);

In index.ts, import Animal, connect to MongoDB, and add some data to the database.

index.ts
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();

Run the file with bun run.

terminal
bun run index.ts
Moo!

As you build your application, refer to the official MongoDB and Mongoose docs.