Node.js Mongoose – Connect to MongoDB
To connect to MongoDB from Node.js using Mongoose package, call connect() function, on the variable referencing to mongoose, with MongoDB Database URI passed as argument to the function.
Mongoose uses a MongoDB connection string to open a connection between your Node.js application and a MongoDB database. After the connection is ready, you can define schemas, create models, and perform database operations through those models.
For official connection behavior and options, refer to the Mongoose connections documentation. If you are using MongoDB Atlas, the MongoDB Mongoose getting started guide explains where to use the Atlas connection string.
Prerequisites before connecting Mongoose to MongoDB
Before running the connection code, make sure that the project has Node.js, npm, Mongoose, and access to a MongoDB server. For a local database, MongoDB must be installed and running on your machine. For a hosted database, such as MongoDB Atlas, you need the correct connection string, username, password, and network access settings.
- Install Node.js and npm.
- Create or open a Node.js project folder.
- Install Mongoose with
npm install mongoose. - Start MongoDB locally, or prepare a valid MongoDB Atlas connection string.
You can quickly confirm that Node.js and npm are available with the following commands.
node -v
npm -v
Basic Mongoose connect() syntax for a local MongoDB database
The basic syntax is to import Mongoose and call mongoose.connect() with the MongoDB database URI. The database name appears at the end of the URI.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name');
In current Node.js applications, 127.0.0.1 is often safer than localhost for local MongoDB connections because some Node.js versions may resolve localhost to an IPv6 address. The following connection string connects to a local database named tutorialkart.
mongoose.connect('mongodb://127.0.0.1:27017/tutorialkart');
Get reference to the active Mongoose database connection
To get a reference to the database specified, use connection() function on Mongoose reference, as shown below :
var db = mongoose.connection;
The mongoose.connection object represents the default Mongoose connection. You can attach event handlers to this connection to detect errors and confirm when the connection is open.
Check whether the Mongoose connection is successful
To check if the connection is successful or not, you may use callback functions : on() and once().
node-js-mongodb-connection.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tutorialkart');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
});
Output
$ node node-js-mongodb-connection.js
Connection Successful!
Connection is successful.
In newer code, it is also common to use async and await because mongoose.connect() returns a promise. This keeps successful connection handling and error handling in one clear flow.
const mongoose = require('mongoose');
async function connectToMongoDB() {
try {
await mongoose.connect('mongodb://127.0.0.1:27017/tutorialkart');
console.log('Connection Successful!');
} catch (error) {
console.error('Connection failed:', error.message);
}
}
connectToMongoDB();
Use environment variables for a MongoDB Atlas Mongoose connection string
For hosted MongoDB databases, avoid writing the username, password, and cluster address directly inside the source file. Store the connection string in an environment variable and read it in your application.
Install dotenv if your local project uses a .env file during development.
npm install dotenv
Example .env entry:
MONGODB_URI=mongodb+srv://username:password@cluster-name.mongodb.net/tutorialkart
Then use the environment variable in your Node.js file.
require('dotenv').config();
const mongoose = require('mongoose');
async function connectToMongoDB() {
try {
await mongoose.connect(process.env.MONGODB_URI);
console.log('Connected to MongoDB');
} catch (error) {
console.error('MongoDB connection error:', error.message);
}
}
connectToMongoDB();
When using a .env file, add it to .gitignore so credentials are not committed to the repository.
.env
node_modules/
Connect Mongoose before running schema and model operations
Mongoose can buffer model operations while the connection is being opened, but relying on buffering can make connection problems harder to identify. A practical approach is to connect to MongoDB first and then start the rest of the application.
const mongoose = require('mongoose');
async function startApp() {
await mongoose.connect('mongodb://127.0.0.1:27017/tutorialkart');
console.log('Database connected');
console.log('Start routes, models, or application logic here');
}
startApp().catch(function (error) {
console.error(error.message);
process.exit(1);
});
This pattern is especially useful in Express applications, where you may want to start listening for requests only after the database connection is ready.
Handle an unsuccessful Mongoose connection
To simulate ‘Connection not successful’ scenario, lets change the port to some incorrect value.
node-js-mongodb-connection.js
var mongoose = require('mongoose');
# incorrect port number
mongoose.connect('mongodb://localhost:ab017/tutorialkart');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
});
If the connection is not successful, you may see the following error message displayed on console.
Output
$ node node-js-mongodb-connection.js
(node:8986) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Slash in host identifier
(node:8986) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The older example above shows how a wrong connection string can fail. In production code, always handle the promise returned by mongoose.connect() with try...catch or .catch(). Also note that JavaScript comments normally use //, so a corrected bad-port test would look like this.
const mongoose = require('mongoose');
async function testBadConnection() {
try {
// incorrect port number for testing connection failure
await mongoose.connect('mongodb://127.0.0.1:9999/tutorialkart');
} catch (error) {
console.error('Connection not successful:', error.message);
}
}
testBadConnection();
When the connection is made without any errors and is open, callback function provided to db.open(‘open’, callback) is executed.
In the event-based example, the callback attached with db.once('open', callback) is executed when the connection opens successfully.
Troubleshooting common Mongoose connection errors
| Mongoose connection issue | Likely reason | What to check |
|---|---|---|
ECONNREFUSED | MongoDB is not running, or the host and port are wrong. | Start MongoDB and verify the URI, such as mongodb://127.0.0.1:27017/tutorialkart. |
Authentication failed | Username, password, database name, or authentication source is incorrect. | Check the credentials and connection string from your MongoDB setup. |
Cannot find module 'mongoose' | Mongoose is not installed in the current project. | Run npm install mongoose from the folder that contains package.json. |
| Connection works locally but fails on Atlas | Network access or credentials may be blocked. | Check Atlas IP access rules, database user permissions, and the full connection string. |
| Script exits before expected database work | The connection or database operation is not awaited. | Use async/await or return promises correctly. |
Mongoose connection FAQ
What is the correct Mongoose connection string for local MongoDB?
A common local URI is mongodb://127.0.0.1:27017/database_name. Replace database_name with the database you want your Node.js application to use.
Should I use localhost or 127.0.0.1 in mongoose.connect()?
For local MongoDB, 127.0.0.1 is often preferred because it avoids possible IPv6 resolution issues with localhost on some Node.js environments.
Does mongoose.connect() create the MongoDB database automatically?
The database name can be included in the connection string, but MongoDB usually creates the database only when data is first written to it. Simply connecting does not necessarily create visible collections.
How do I connect Mongoose to MongoDB Atlas?
Use the Atlas connection string with mongoose.connect(). Store it in an environment variable, verify your database user credentials, and make sure your current IP address is allowed in the Atlas network access settings.
Why does my Mongoose connection fail even after installing Mongoose?
Installing Mongoose only adds the package to your project. A failed connection usually points to a MongoDB server issue, an incorrect URI, authentication problems, blocked network access, or a missing await/catch around mongoose.connect().
Editorial QA checklist for this Mongoose MongoDB connection tutorial
- The tutorial shows the original
mongoose.connect()syntax and also includes a currentasync/awaitconnection pattern. - The local MongoDB examples explain the database URI, host, port, and database name clearly.
- The page explains why
127.0.0.1may be preferable tolocalhostfor local Mongoose connections. - The MongoDB Atlas section avoids hard-coded credentials and uses environment variables.
- The troubleshooting table covers practical connection failures, including server, URI, authentication, package installation, and promise-handling issues.
Conclusion
In this Node.js Tutorial – Node.js Mongoose – Connect to MongoDB, we have learnt to connect to MongoDB using Mongoose, get the reference to Database, check if the connection is successful or not.
The main step is to call mongoose.connect() with a valid MongoDB URI. For local development, use a local URI such as mongodb://127.0.0.1:27017/tutorialkart. For hosted databases, keep the connection string in an environment variable and handle connection errors before running database operations.
TutorialKart.com