StackKit LogoStackKit
ModulesDatabase

Mongoose

Elegant MongoDB object modeling for Node.js. Mongoose provides schema-based data modeling with built-in validation and query helpers.

Mongoose is the most widely used MongoDB ODM for Node.js. It lets you define schemas for your data, and provides a clean interface for querying and validating MongoDB documents. StackKit generates a working connection and an example model so you can start writing queries right away.

Compatible frameworks

Mongoose is available for Express projects only.

If you need MongoDB in a Next.js project or want to use a different database alongside MongoDB, consider using Prisma with the MongoDB provider instead.

Installation

In a new project

npx stackkit@latest create my-api --framework express --database mongoose
pnpm dlx stackkit@latest create my-api --framework express --database mongoose
yarn dlx stackkit@latest create my-api --framework express --database mongoose
bun x stackkit@latest create my-api --framework express --database mongoose

In an existing project

npx stackkit@latest add
# Navigate to: Database → Mongoose

What gets generated

  • src/lib/db.ts — MongoDB connection function using Mongoose. Connects once on startup and reuses the connection.
  • src/lib/models/User.ts — An example User model to show you the pattern for defining schemas.
  • .env.example — A DATABASE_URL entry with the correct format.

Setup

Copy your environment file

cp .env.example .env

Set your MongoDB connection URL

Open .env and update DATABASE_URL:

# Local MongoDB
DATABASE_URL="mongodb://localhost:27017/my-database"

# With authentication
DATABASE_URL="mongodb://username:password@localhost:27017/my-database?authSource=admin"

# MongoDB Atlas (cloud)
DATABASE_URL="mongodb+srv://username:[email protected]/my-database"

Make sure MongoDB is accessible

If you're running MongoDB locally, verify it's running:

# macOS (Homebrew)
brew services list | grep mongodb

# Linux (systemd)
systemctl status mongod

# Or just try to connect
mongosh

If you're using MongoDB Atlas, make sure your IP address is whitelisted in the Atlas dashboard.

Start the development server

npm run dev

The database connection is established automatically when your app starts.

Using the connection and models

The generated src/lib/db.ts connects to MongoDB automatically. You can import it in your app's entry point or it may already be called in the generated server setup.

To create your own models, follow the pattern in the generated User.ts:

import mongoose, { Schema, model } from "mongoose";

interface IPost {
  title: string;
  body: string;
  author: string;
  createdAt: Date;
}

const postSchema = new Schema<IPost>({
  title: { type: String, required: true },
  body: { type: String, required: true },
  author: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
});

export const Post = model<IPost>("Post", postSchema);

Then use it in your routes or controllers:

import { Post } from "@/lib/models/Post";

// Create
const post = await Post.create({ title: "Hello", body: "World", author: "Alice" });

// Find
const posts = await Post.find({ author: "Alice" });

// Update
await Post.findByIdAndUpdate(id, { title: "Updated" });

Next steps

  • Prisma — Alternative ORM with support for PostgreSQL, MySQL, SQLite and MongoDB
  • Troubleshooting — Common connection issues

On this page