Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Integrating Node.js with MongoDB

1. Introduction

MongoDB is a NoSQL database designed for scalability and flexibility, while Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Integrating these technologies allows for efficient handling of dynamic data in web applications.

2. Setup

2.1 Prerequisites

  • Node.js installed (version 12 or later)
  • MongoDB installed and running locally or remotely
  • Basic understanding of JavaScript and Node.js

2.2 Installing Dependencies

First, create a new Node.js project and install the necessary packages.

mkdir myapp
cd myapp
npm init -y
npm install mongodb

3. Database Connection

3.1 Connecting to MongoDB

Use the following code to connect to MongoDB:

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

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

async function run() {
    try {
        await client.connect();
        console.log('Connected to MongoDB');
    } finally {
        await client.close();
    }
}

run().catch(console.dir);

4. CRUD Operations

4.1 Create

To insert a document into a collection:

async function createDocument(db) {
    const collection = db.collection('users');
    const result = await collection.insertOne({ name: 'John Doe', age: 30 });
    console.log(`New user created with the following id: ${result.insertedId}`);
}

4.2 Read

To retrieve documents from a collection:

async function findDocuments(db) {
    const collection = db.collection('users');
    const users = await collection.find({}).toArray();
    console.log(users);
}

4.3 Update

To update a document in a collection:

async function updateDocument(db) {
    const collection = db.collection('users');
    const result = await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });
    console.log(`${result.modifiedCount} document(s) was/were updated.`);
}

4.4 Delete

To delete a document from a collection:

async function deleteDocument(db) {
    const collection = db.collection('users');
    const result = await collection.deleteOne({ name: 'John Doe' });
    console.log(`${result.deletedCount} document(s) was/were deleted.`);
}

5. Best Practices

  • Always close database connections properly to prevent memory leaks.
  • Use indexes to improve query performance.
  • Validate data before insertion to maintain data integrity.
  • Handle exceptions using try-catch blocks to avoid application crashes.

6. FAQ

What is MongoDB?

MongoDB is a document-oriented NoSQL database used for high volume data storage.

How do I connect to a remote MongoDB server?

Update the connection URL to include the remote server's address and authentication details if required.

Can I use MongoDB with other programming languages?

Yes, MongoDB has official drivers for various programming languages like Python, Java, and PHP.