Skip to content

Guide · Open source

How to use Mongoose: install, define schemas and query MongoDB

Updated · written with AI from the project's own documentation and checked against our catalogue data

Mongoose is an object modeling tool for MongoDB, used from JavaScript and Node.js. It lets you describe your documents with a schema, including field types, validators, defaults and indexes, and then gives you model objects to save, find and update data. This guide walks through installing it, connecting to MongoDB, defining a model and running basic queries, so you can get a working data layer in your app.

MongooseAutomattic/mongoose · ★ 27.5k · MIT

Quick start

  1. 1Install Node.js and MongoDB. Install Node.js and MongoDB first, as the Mongoose installation section requires both.
  2. 2Install the mongoose package. Run npm install mongoose in your project folder, or use pnpm, Yarn or Bun.
  3. 3Connect to your database. Call mongoose.connect with a mongodb:// URI. If the local connection fails, try 127.0.0.1 instead of localhost.
  4. 4Define a schema. Create a Schema describing your fields, types, validators and defaults.
  5. 5Create a model. Pass the singular model name and your schema to mongoose.model; Mongoose uses the plural collection name.
  6. 6Save and query documents. Create an instance, call save, then use find or findOne to read data.

What you need before you install Mongoose

Mongoose needs Node.js and MongoDB. The source asks you to install both first, then add the mongoose package to your project with your preferred package manager.

Mongoose is specifically for MongoDB. If you want a SQL database, it is not the right tool. Beginners with no Node.js or MongoDB experience should learn those basics first.

  • Node.js
  • MongoDB (see the MongoDB downloads page)

Install Mongoose with npm or another package manager

Run the install command in your project folder. The README also lists commands for pnpm, Yarn and Bun.

npm install mongoose

Connect your app to MongoDB

If your app uses only one database, use mongoose.connect. If you need additional connections, use mongoose.createConnection. Both accept a mongodb:// URI, or the parameters host, database, port and options.

Once connected, the open event fires on the Connection instance. With mongoose.connect, that Connection is mongoose.connection.

If the local connection fails, try 127.0.0.1 instead of localhost, since issues can arise when the local hostname has changed. Mongoose also buffers commands until it is connected, so you can define models and run queries before the connection is ready.

await mongoose.connect('mongodb://127.0.0.1/my_database');

Define a schema and model

Models are defined through the Schema interface. A schema describes the structure of your documents and the types of data you store. Beyond structure, a schema can also define validators, defaults, getters, setters, indexes, middleware, methods, statics, plugins and pseudo-JOINs (populate).

Mongoose looks for the plural form of the model name. A model named Ticket uses the tickets collection, not ticket.

  • Validators (async and sync)
  • Defaults
  • Getters and setters
  • Indexes
  • Middleware
  • Methods and statics
  • Plugins
  • pseudo-JOINs via populate
const BlogPost = new Schema({ author: ObjectId, title: String, body: String, date: Date }); const MyModel = mongoose.model('Ticket', mySchema);

Save, find and update documents

Create an instance from your model, set its fields and call save. To read data, call find on the model, or findOne, findById and update. Full query details are in the Mongoose queries documentation.

const instance = new MyModel(); instance.my.key = 'hello'; await instance.save(); await MyModel.find({}); const found = await MyModel.findOne({ /* ... */ });

Use createConnection for multiple databases

If you open a separate connection with mongoose.createConnection, create the model through that connection. Using mongoose.model on the default connection with a separate connection will not work as expected, because the model is not attached to the active connection.

  • Right: conn.model('ModelName', schema)
  • Wrong for a separate connection: mongoose.model('ModelName', schema)
const conn = mongoose.createConnection('your connection string'); const MyModel = conn.model('ModelName', schema); const m = new MyModel(); await m.save();

What people use it for

  • Storing blog posts with an author, title, body and date, as in the README's BlogPost example.
  • Adding validation rules such as a minimum age or a regex match to user data before it is saved.
  • Running an app that reads from one main database and a second database through createConnection.
  • Adding middleware that runs before a document is saved, such as sending a notification.
  • Browsing and editing your data with Mongoose Studio, a free browser-based MongoDB GUI built by the Mongoose team.

Frequently asked questions

Is Mongoose free to use?

Yes. Mongoose is released under the MIT licence and is open source. The README also mentions an optional Tidelift subscription for commercial support, which is separate from the library itself.

How do I install Mongoose?

Install Node.js and MongoDB first, then run npm install mongoose in your project folder. The README also lists pnpm, Yarn and Bun commands.

Does Mongoose work with Deno?

The README says Mongoose supports Deno, but describes this as alpha support. It shows an example using Deno's createRequire for CommonJS modules.

Why does my Mongoose connection fail on localhost?

The README suggests trying 127.0.0.1 instead of localhost, because issues can arise when the local hostname has been changed.

Why does save not work with my second connection?

If you used mongoose.createConnection, define the model with conn.model(). Using mongoose.model() on the default connection does not attach the model to your separate active connection.

What are the alternatives to Mongoose?

Comparable projects named in this directory are Prisma, TypeORM and the MongoDB Node.js driver. Mongoose adds schemas and model objects on top of MongoDB, while the driver is lower-level.

New agent skills, repos and AI tools — every week

The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.

Our verdict

Mongoose suits Node.js developers building an app on MongoDB who want schemas, validation and middleware on top of their documents, or who need several connections. It is not a good choice if you do not use MongoDB or want a SQL database, and beginners should first learn Node.js and MongoDB basics.

Install options & downloads