Node.js Mongoose – Installation
In this tutorial, we shall learn to install Mongoose package using npm (Node Package Manager).
Mongoose is an Object Data Modeling library for MongoDB and Node.js. After installing it in a Node.js project, you can define schemas, create models, validate data, and connect your application code to a MongoDB database in a structured way.
Check Node.js, npm, and MongoDB before installing Mongoose
It is assumed that you have already installed Node.js and MongoDB. If incase not, then you may refer the below links.
You can also verify Node.js and npm from the terminal before installing the package.
node -v
npm -v
The commands should print version numbers. If either command is not found, install Node.js first because npm is included with the standard Node.js installation.
Create a Node.js project for the Mongoose package
Mongoose should usually be installed inside a project folder, not globally. Create a project directory and initialize a package.json file if your project does not already have one.
mkdir mongoose-demo
cd mongoose-demo
npm init -y
The package.json file records project dependencies, scripts, and metadata. When you install Mongoose, npm adds it to the project dependencies so the same package can be installed again on another machine using npm install.
Install Mongoose in Node.js using npm
To install Mongoose package, use npm (Node Package Manager). Open a terminal and run the following command.
$ npm install mongoose
$ npm install mongoose
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN mongoose_tutorial@1.0.0 No repository field.
+ mongoose@5.0.3
added 20 packages in 3.936s
The exact terminal output can differ based on the npm version, operating system, and the current Mongoose version. In a current project, npm may install a newer Mongoose release than the version shown in the older sample output above.
You can check the installed package from your project folder with the following command.
npm list mongoose
For the official package page and version details, refer to the Mongoose package on npm. For the official getting started guide, refer to the Mongoose documentation.
Install Mongoose with a specific version when needed
For most new applications, installing the latest stable Mongoose package is enough. In an existing application, you may need to install a specific major version to match the codebase or migration plan.
npm install mongoose@8
Use a fixed version only when the project requires it. Before changing major versions in an existing application, read the relevant Mongoose migration guide because model behavior, connection behavior, and TypeScript support can change between major releases.
Import Mongoose in a Node.js script
To use Mongoose in Node.js Script File, include require statement with mongoose package.
var mongoose = require('mongoose');
If your project uses ES modules, you can import Mongoose with import syntax instead.
import mongoose from 'mongoose';
Use one module style consistently in the same project. CommonJS projects usually use require(), while ES module projects usually set "type": "module" in package.json and use import.
Connect Mongoose to a local MongoDB database
Installing the package only adds Mongoose to the project. To use it, your Node.js application must connect to a MongoDB server. The following small example connects to a local MongoDB database named tutorialkart.
const mongoose = require('mongoose');
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/tutorialkart');
console.log('Connected to MongoDB with Mongoose');
}
main().catch(function (error) {
console.error('Mongoose connection error:', error.message);
});
Run the file only after the MongoDB server is running. If you use MongoDB Atlas or another hosted MongoDB service, replace the local connection string with the connection string from that service, and keep credentials outside the source code.
Verify Mongoose installation with a simple schema and model
The quickest practical check is to define a schema, create a model, and insert one document. The example below creates a Student model and saves one student document.
const mongoose = require('mongoose');
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/tutorialkart');
const studentSchema = new mongoose.Schema({
name: String,
age: Number
});
const Student = mongoose.model('Student', studentSchema);
const student = await Student.create({
name: 'Arjun',
age: 20
});
console.log(student);
await mongoose.connection.close();
}
main().catch(function (error) {
console.error(error);
});
If the script inserts and prints a document, Mongoose is installed correctly and the database connection is working. In a real application, keep the schema, model, and database connection in separate files as the project grows.
Common npm and MongoDB errors while installing Mongoose
| Error or symptom | Likely cause | What to check |
|---|---|---|
npm: command not found | Node.js or npm is not installed correctly. | Install Node.js and check node -v and npm -v. |
Cannot find module 'mongoose' | Mongoose is not installed in the current project folder. | Run npm install mongoose in the folder that contains package.json. |
| Connection refused to MongoDB | MongoDB server is not running, or the host and port are wrong. | Start MongoDB and check the connection string, for example mongodb://127.0.0.1:27017/dbname. |
| Authentication failed | The MongoDB username, password, database, or connection options are incorrect. | Verify credentials and avoid hard-coding them in source files. |
| Version mismatch after copying a project | node_modules is missing or dependencies were not installed. | Run npm install in the project folder. |
When to use Mongoose instead of the MongoDB Node.js driver
Mongoose is useful when your Node.js application benefits from schemas, models, validation, middleware, and a consistent data layer. The MongoDB Node.js driver is closer to MongoDB itself and can be a better fit when you want lower-level control without an ODM layer.
For many Express and Node.js applications, Mongoose is chosen because it keeps document structure and validation rules in application code. For small scripts or database administration tasks, the native driver may be simpler.
Mongoose installation FAQ
Should I install Mongoose globally or inside my Node.js project?
Install Mongoose inside the project with npm install mongoose. A local installation records the package in package.json and makes the project easier to install on another system.
Do I need to install the MongoDB Node.js driver separately for Mongoose?
No. Installing Mongoose installs the MongoDB driver dependency required by Mongoose. Install the native driver separately only if your project also uses the driver directly.
Can I use Mongoose with MongoDB Atlas?
Yes. Use the MongoDB Atlas connection string in mongoose.connect(). Keep the username, password, and database URI in environment variables instead of writing them directly in your source code.
Why does Node.js say it cannot find the mongoose module?
This usually means Mongoose is not installed in the project folder that runs the script. Go to the folder containing package.json, run npm install mongoose, and then run the script again.
Which import style should I use for Mongoose: require or import?
Use require('mongoose') in CommonJS projects. Use import mongoose from 'mongoose' in ES module projects where "type": "module" is configured in package.json.
Editorial QA checklist for this Mongoose installation tutorial
- The tutorial tells the reader to install Mongoose in a project folder, not as a global npm package.
- The original npm install command and the older sample output are preserved, while the text explains that actual installed versions may differ.
- The page includes both CommonJS
require()and ES moduleimportusage notes without mixing them in one example. - The connection example uses
127.0.0.1for a local MongoDB connection and reminds readers to keep hosted database credentials out of source code. - The troubleshooting table covers npm, missing module, MongoDB connection, authentication, and dependency reinstall issues.
Summary of installing Mongoose in Node.js
In this tutorial, we have learnt how to install a Mongoose package and start using its reference.
The basic installation step is npm install mongoose from inside a Node.js project folder. After installation, import Mongoose, connect it to MongoDB, and then define schemas and models for the documents your application stores.
TutorialKart.com