Menu
CoddyTech

Connecting to MongoDB

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 3 of 29.

Your program reaches MongoDB through a client object. Import MongoClient and create one with a connection address. The address below names MongoDB on the same computer: localhost. The number 27017 is the port where that database service listens.

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('shop');
const orders = db.collection('orders');

The first line configures the client; the next two select a database and collection. These lines do not read records. In Coddy the connection is provided by a practice database that resets on Run. A normal MongoDB deployment stores data beyond an application restart.

Create the client at module level so requests reuse it. Creating a client inside the request function would create a new connection pool on every request with the real driver.

challenge icon

Challenge

Easy

Edit connection.js. Replace the placeholder with a client using mongodb://localhost:27017, the shelf database and its books collection.

Create these values outside selectBooks(). Keep that function returning the selected collection, so every request reuses it. The supplied route reads the collection for you. Try Run: GET /result should list Dune, Kindred and Emma. No insert or route code is needed.

The supplied GET /reuse route returns {"same":true} when repeated calls receive the same collection handle.

Try it yourself

import { MongoClient } from 'mongodb';
// Create the client, select the database, and replace this placeholder.
const books = null;
export function selectBooks() {
    return books;
}

All lessons in Databases with MongoDB

Practice on your own: Express playground