Menu
CoddyTech

A Database Module

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

One file that opens the database and holds every route grows hard to read, and any second file that needs books would have to connect again.

Move the connection into a module of its own. A module's top-level code runs once, the first time any file imports it, and every later import gets the same exports. So the client, the index and the seed run once, however many files import the collections. Top-level await works in a module, and the importing file waits for it to finish.

// store.js
import { MongoClient } from 'mongodb';

const client = new MongoClient('mongodb://localhost:27017');
export const orders = client.db('shop').collection('orders');
await orders.createIndex({ number: 1 }, { unique: true });
// server.js
import { orders } from './store.js';
challenge icon

Challenge

Easy
  • server.js now imports books and ratings from ./db.js, so it cannot start yet.
  • In db.js, create the client, export both collections, create the ISBN index, and seed the books and the authors.

Press Run: every route answers as before. Send GET /books twice: still three books.

Try it yourself

import { MongoClient } from 'mongodb';
import { authorList } from './authors.js';

const bookList = [
    { 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' },
];

// Create the client here, export the books and ratings collections,
// create the ISBN index, and seed bookList and authorList.
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