CodeBlanks Logo Icon CodeBlanks

Mongoose

Learn MongoDB connection with the Mongoose ODM.

What is Mongoose?

Mongoose is the most popular MongoDB ODM (Object Data Modeling) for Node.js. It lets you model MongoDB documents as JavaScript objects; it simplifies types, validation, and query building.

Install: npm install mongoose. Connect: mongoose.connect("mongodb://localhost:27017/mydb"). Mongoose is an abstraction over the raw MongoDB driver; you write safer queries with less code. It is a common choice in production.

Establishing a connection

To connect to MongoDB with Mongoose: mongoose.connect(uri). The URI format is mongodb://[user:pass@]host:port/dbname. The connection is asynchronous; you await it.

Connection state is read from mongoose.connection.readyState: 0 (disconnected), 1 (connected), 2 (connecting), 3 (disconnecting). You catch errors with mongoose.connection.on("error", cb). To close the connection call mongoose.disconnect(). In production the connection pool size is set with the { poolSize: 10 } option; this controls the number of concurrent queries.

Practice Log the type of mongoose

Import the mongoose module. Log typeof mongoose.

Starter code

index.js
// import the module

// log its type

Sample solution

index.js
const mongoose = require("mongoose");
console.log(typeof mongoose);

Expected output

object

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is Mongoose installed?

  • npm install mongoose Correct answer
  • pip install mongoose
  • apt get mongoose
  • brew mongoose

Explanation: Mongoose is installed with npm.

2 Complete the module name

Question
const mongoose = require("____")
Answer
const mongoose = require("mongoose")

Explanation: The Mongoose module loads as 'mongoose'.

3 Match each piece to its role

Term Meaning
mongoose MongoDB ODM
npm install mongoose Installs the module
require("mongoose") Imports the module
mongoose.connect Connects

All lessons in Advanced