Connecting to MongoDB
Learn how to connect to MongoDB using mongosh and the Node.js MongoDB driver with connection strings.
Connecting to MongoDB
Before your app can read or write any data, it needs to connect to MongoDB. Every connection uses a connection string — a single line of text that tells your app where MongoDB is running and how to reach it.
What is a Connection String?
A connection string is like an address for your database. It tells your app:
- What protocol to use
- Where the server is running
- Which port to connect on
- Which database to use
- Any extra options like authentication
The basic structure looks like this:
mongodb://username:password@host:port/databaseFor a local MongoDB server with no username or password, it simplifies to:
mongodb://localhost:27017Let's break that down:
| Part | Meaning |
|---|---|
mongodb:// | The protocol — tells the driver this is a MongoDB connection |
localhost | The server is running on your own machine |
27017 | The port MongoDB listens on by default |
Connecting with mongosh
When you open mongosh without any arguments, it automatically connects to mongodb://localhost:27017. But you can also pass a connection string directly:
mongosh "mongodb://localhost:27017"To connect directly to the school database:
mongosh "mongodb://localhost:27017/school"Once connected, switch to the school database:
use schoolCheck which database you are currently using:
dbOutput:
schoolList all collections in the school database:
show collectionsOutput:
studentsConnecting from Node.js
To connect to MongoDB from a Node.js application, you need the official MongoDB Node.js driver.
Install it
npm install mongodbBasic connection
Create a file called connect.js:
const { MongoClient } = require('mongodb');
// Connection string pointing to our local MongoDB server
const uri = 'mongodb://localhost:27017';
// Create a client
const client = new MongoClient(uri);
async function main() {
// Connect to the server
await client.connect();
console.log('Connected to MongoDB');
// Select the school database
const db = client.db('school');
// Select the students collection
const students = db.collection('students');
// Find all students
const allStudents = await students.find().toArray();
console.log(allStudents);
}
main()
.catch(console.error)
.finally(() => client.close());Run it:
node connect.jsOutput:
Connected to MongoDB
[
{
_id: ObjectId('64a1f2c3e4b0a1b2c3d4e5f6'),
name: 'Ali Hassan',
age: 16,
grade: '10th'
}
]Your Node.js app is now talking to your MongoDB school database.
Connection Options
You can add options to the connection string to control how the connection behaves. Options go after a ? at the end:
mongodb://localhost:27017/school?option1=value1&option2=value2Here are the most useful ones:
| Option | What it does | Example |
|---|---|---|
connectTimeoutMS | How long to wait before giving up on connecting | connectTimeoutMS=5000 |
maxPoolSize | Max number of simultaneous connections | maxPoolSize=10 |
authSource | Which database to authenticate against | authSource=admin |
For a local development connection you rarely need these. They matter more in production.
Connection with Authentication
If your MongoDB server has a username and password set up, include them in the connection string:
mongodb://username:password@localhost:27017/schoolIn Node.js:
const uri = 'mongodb://admin:secret123@localhost:27017/school';
const client = new MongoClient(uri);Never hardcode usernames and passwords in your code. Use environment variables instead:
const uri = process.env.MONGODB_URI;Store the actual connection string in a .env file and add .env to your .gitignore.
Common Connection Errors
Error: connect ECONNREFUSED 127.0.0.1:27017
MongoDB is not running. Start it:
- Windows: check Services and start the MongoDB service
- macOS:
brew services start mongodb-community - Linux:
sudo systemctl start mongod
Error: Authentication failed
Wrong username or password in your connection string. Double check them.
Error: MongoServerSelectionError
MongoDB is running but your app cannot reach it. Check your firewall settings or whether the port 27017 is blocked.
Connecting to the School Database
From this point forward, every example in this guide connects to the school database. In mongosh:
use schoolIn Node.js, always use this as your starting point:
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('school');We will use this same pattern in every file going forward.
In the Mongoose section, we will use a cleaner way to connect — mongoose.connect(). But understanding the raw MongoDB driver connection string is important because Mongoose uses the exact same string format underneath.