Node.js MongoDB: Create Database

Welcome to The Coding College! This tutorial will guide you through the steps of creating a database in MongoDB using Node.js. MongoDB does not require explicit commands to create a database; it creates one automatically when data is first inserted.


Why Use MongoDB?

  • Flexibility: Schema-less design allows quick adjustments to your data structure.
  • Scalability: Ideal for handling large-scale applications.
  • Ease of Integration: Perfectly complements Node.js with JSON-like documents.

Prerequisites

Before starting, ensure the following:

  1. MongoDB Installed: Install MongoDB.
  2. Node.js Installed: Install Node.js.
  3. MongoDB Driver Installed: Run the command below to install the MongoDB driver: npm install mongodb

Step 1: Set Up Connection

Create a file createDatabase.js and establish a connection to MongoDB:

const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017'; // Default MongoDB URL
const client = new MongoClient(url);

// Database Name
const dbName = 'myNewDatabase'; // Name of the new database

async function createDatabase() {
  try {
    // Connect to the MongoDB server
    await client.connect();
    console.log('Connected to MongoDB server.');

    // Create or select the database
    const db = client.db(dbName);
    console.log(`Database '${dbName}' selected.`);
  } catch (err) {
    console.error('Error connecting to MongoDB:', err.message);
  } finally {
    // Close the connection
    await client.close();
    console.log('Connection closed.');
  }
}

createDatabase();

Step 2: Insert Data to Create Database

In MongoDB, a database is not created until it contains at least one collection with data. Modify the script to insert a sample document:

async function createDatabaseWithCollection() {
  try {
    await client.connect();
    console.log('Connected to MongoDB server.');

    const db = client.db(dbName);

    // Create a collection and insert a document
    const collection = db.collection('users');
    const result = await collection.insertOne({ name: 'John Doe', age: 30 });
    console.log('Document inserted:', result.insertedId);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
    console.log('Connection closed.');
  }
}

createDatabaseWithCollection();

Step 3: Verify Database Creation

  1. Open the MongoDB Shell or use MongoDB Compass (GUI).
  2. Run the following command in the shell to see all databases: show dbs You should see myNewDatabase listed if it contains at least one document.

Step 4: View Data

Query the users collection to ensure the document was successfully inserted:

async function viewData() {
  try {
    await client.connect();
    console.log('Connected to MongoDB server.');

    const db = client.db(dbName);
    const collection = db.collection('users');

    const data = await collection.find({}).toArray();
    console.log('Data in collection:', data);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
    console.log('Connection closed.');
  }
}

viewData();

Best Practices

  1. Use Environment Variables: Secure sensitive information like the MongoDB URL using a .env file.
  2. Database Names: Use clear and meaningful database names to maintain organization.
  3. Indexes: Add indexes to collections to optimize query performance.
  4. Connection Pooling: Reuse connections for better scalability in production.

Example Output

When you run the script, you should see:

Connected to MongoDB server.
Database 'myNewDatabase' selected.
Document inserted: 64c12345abcd6789ef123456
Connection closed.

Conclusion

Creating a MongoDB database using Node.js is straightforward. MongoDB’s dynamic nature allows you to start building applications quickly without worrying about rigid schemas. For more tutorials, guides, and coding tips, visit The Coding College.

Leave a Comment