Menu
CoddyTech

Connecting to MongoDB

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 1 of 18.

An array in a server is lost every time the server stops. A database keeps the data. MongoDB is a database server that stores documents: JSON-like objects. Documents live in collections, and collections live in a database.

import { MongoClient } from 'mongodb';

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

await movies.insertOne({ title: 'Alien', year: 1979 });
const all = await movies.find().toArray();

The client talks to the database server at that address. insertOne stores one document. find() gives a cursor, an object that reads the results only when asked, and toArray() reads them all into an array. Each call goes to the database, so each one needs await.

Here, Run starts an empty MongoDB in memory and the Data tab shows its collections. The starter seeds three books with insertMany, which takes an array of documents.

challenge icon

Challenge

Easy
  • Add GET /books: it answers every document in the books collection as a JSON array.

Press Run and open the Data tab to see the three books. Then send GET /books.

Try it yourself

import express from 'express';
import { MongoClient } from 'mongodb';

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

await books.insertMany([
    { title: 'Dune', author: 'Frank Herbert', year: 1965, isbn: '9780441013593', genre: 'scifi' },
    { title: 'Kindred', author: 'Octavia E. Butler', year: 1979, isbn: '9780807083697', genre: 'scifi' },
    { title: 'Emma', author: 'Jane Austen', year: 1815, isbn: '9780141439587', genre: 'classic' },
]);

const app = express();
app.use(express.json());

// Every error answers { error: message }.
function sendError(res, status, message) {
    res.status(status).json({ error: message });
}

app.get('/', (req, res) => {
    res.send('Bookshelf API');
});

// Add GET /books here.

app.listen(3000, () => {
    console.log('Bookshelf is running on port 3000');
});
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Databases with MongoDB