Using MongoDB in Node.js

Connect to MongoDB and perform CRUD operations with the official Node.js driver, then serve data through an Express API.

🎯 Introduction

So far, we have entered database commands in mongosh. In real applications, backend code performs these operations: a user sends a request, the Node.js service queries MongoDB, and the result is returned to the browser.

By the end, you will connect to MongoDB using the official mongodb driver, write complete CRUD operations in Node.js, and create an Express endpoint that returns a user list. This connects your database knowledge to backend development.


🧱 Installation and Preparation

mongodb is MongoDB's official Node.js driver. Maintained by the MongoDB team, it provides the tools to connect to databases and work with collections, and is a common choice in the Node.js ecosystem.

This article and course were written and tested with Node.js v22 LTS and mongodb 7.x, the official driver. Create a project directory, initialize it, and install the package:

mkdir node-mongo && cd node-mongo
npm init -y
npm install mongodb

Before writing code, check that the MongoDB container is running:

docker ps

If mongo-demo is missing, start it with docker start mongo-demo.

All examples use the user collection in blog_demo, with the same username, age, and city fields. If it is empty, insert a few documents in mongosh or use the code below to add them.

✨ Connecting with MongoClient

MongoDB uses a connection string, similar to a URL, specifying the protocol, credentials, host, and port:

mongodb://root:123456@localhost:27017

Use MongoClient to connect, then obtain references to the database and collection:

db.js
const { MongoClient } = require('mongodb');

const url = 'mongodb://root:123456@localhost:27017';
const client = new MongoClient(url);

async function main() {
    try {
        await client.connect();
        console.log('Connected successfully');

        const db = client.db('blog_demo');
        const user = db.collection('user');

        // Use the user collection for subsequent operations
    } finally {
        await client.close();
    }
}

main();

Here are the key steps:

  • new MongoClient(url): Creates a client instance without connecting yet.
  • await client.connect(): Establishes the connection. Network or credential errors are thrown here.
  • client.db('blog_demo'): Selects the database; db.collection('user') selects the collection. These calls return handles without accessing the database.
  • try/finally ensures client.close() runs even if an operation fails, closing connections so the script can exit.

Think of client as placing a phone call, db as reaching the right department, and collection as finding the person responsible. Once you reach them, you can begin the actual work.

In real projects, keep passwords in environment variables, for example in a .env file read through process.env, rather than hardcoding them and risking exposure in a repository. Hardcoding is sufficient for these learning examples, but remember the distinction.

🛠 Complete CRUD Operations

The following crud.js covers the everyday operations: inserting, listing users, finding one by ID, updating, and deleting.

crud.js
const { MongoClient, ObjectId } = require('mongodb');

const url = 'mongodb://root:123456@localhost:27017';
const client = new MongoClient(url);

async function main() {
    try {
        await client.connect();
        const user = client.db('blog_demo').collection('user');

        // Insert a user
        const result = await user.insertOne({
            username: 'Xiao Mei',
            age: 22,
            city: 'Shenzhen',
        });
        console.log('User inserted, _id =', result.insertedId);

        // List users
        const list = await user.find().toArray();
        console.log('Users:', list);

        // Find a user by ID
        const one = await user.findOne({ _id: new ObjectId(result.insertedId) });
        console.log('User by ID:', one);

        // Update a user
        await user.updateOne(
            { _id: new ObjectId(result.insertedId) },
            { $set: { age: 23 } }
        );

        // Delete a user
        await user.deleteOne({ _id: new ObjectId(result.insertedId) });
    } finally {
        await client.close();
    }
}

main();

Run node crud.js to see the insert, read, update, and delete operations execute in sequence.

Remember that an ObjectId-valued _id is a special object type, not a plain string. Import ObjectId from mongodb and convert an ID string with new ObjectId(idString) before querying. Passing the string directly will not match, a common beginner mistake.

💡 Creating an Express Endpoint

Let's bring this together in an Express endpoint: GET /users returns the user list. This example uses Express 5.x. Install it first:

npm install express
server.js
const express = require('express');
const { MongoClient } = require('mongodb');

const url = 'mongodb://root:123456@localhost:27017';
const client = new MongoClient(url);

const app = express();

app.get('/users', async (req, res) => {
    const user = client.db('blog_demo').collection('user');
    const list = await user.find().toArray();
    res.json(list);
});

async function main() {
    await client.connect();

    app.listen(3000, () => {
        console.log('Server listening at http://localhost:3000');
    });
}

main();

Unlike a one-off script, a server keeps running. Connect once at startup and reuse the client for subsequent requests; do not connect and close for every request.

Run node server.js, then visit http://localhost:3000/users to see the user list as JSON. You now have a complete path from browser to Node.js to MongoDB and back.


❓ Questions and Answers

Q1: Why does my script report a connection failure?

Check that mongo-demo is running with docker ps, and that the connection string's username, password, and port match the container configuration. A stopped container or incorrect password will prevent a connection.

Q2: Do client.db() and db.collection() access the database?

No. They only return handles. Network access happens when connecting and executing operations such as find() and insertOne(). The handle calls do not fail just because the database or collection does not exist yet.

Q3: Why does querying _id as a string return null?

The _id values in these examples are ObjectIds, which do not equal strings. Import ObjectId from mongodb and use findOne({ _id: new ObjectId(id) }).

Q4: Should I call client.close() after every operation?

Close the client when a one-off script finishes so the process can exit. Long-running services such as Express connect once at startup and reuse the client, closing it when the process shuts down.

Q5: What is the risk of hardcoding a password?

Anyone who sees the code, including through a Git repository, can see the database password. Use environment variables in real projects and include .env in .gitignore.


🧪 Exercises

Exercise 1: Using this article's examples, write getUserByName, accepting a username and returning the matching user document, or null if no user matches.

crud.js
const { MongoClient } = require('mongodb');

const url = 'mongodb://root:123456@localhost:27017';
const client = new MongoClient(url);

async function getUserByName(username) {
    // Write your code here
}

Exercise 2: Add GET /users/:name to the Express server. Find a user by the username in the route parameter and return the document as JSON.

server.js
app.get('/users/:name', async (req, res) => {
    // Write your code here
});

🎉 You can now use MongoDB from Node.js! Next, we will introduce Mongoose, which adds field constraints and validation to make data operations more consistent and easier to manage.