Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Database Interaction (e.g., MongoDB)

Database Interaction (e.g., MongoDB)

 Node.js is commonly used for interacting with databases, including NoSQL databases like MongoDB. In this guide, we'll walk through the steps to interact with a MongoDB database using the popular MongoDB Node.js driver.
 

Step 1: Install Dependencies

To work with MongoDB in Node.js, you'll need to install the MongoDB Node.js driver. You can do this using npm:

npm install mongodb
 

Step 2: Connect to MongoDB

In your Node.js application, you'll need to create a connection to your MongoDB database using the MongoClient from the MongoDB driver.

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

// Connection URL and database name
const url = 'mongodb://localhost:27017';
const dbName = 'mydb';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

// Connect to the MongoDB server
client.connect((err) => {
  if (err) {
    console.error('Error connecting to MongoDB:', err);
    return;
  }
  
  // Connected successfully to the server
  console.log('Connected to MongoDB');
  
  // Use the connected client to interact with the database
  const db = client.db(dbName);
  
  // Perform database operations here...
  
  // Close the connection when done
  client.close();
});
 

Step 3: Perform Database Operations

Once connected to the database, you can perform various operations such as inserting, updating, deleting, and querying data. Here are some common operations:

Inserting Data:

const collection = db.collection('mycollection');
const document = { name: 'John', age: 30 };

collection.insertOne(document, (err, result) => {
  if (err) {
    console.error('Error inserting document:', err);
    return;
  }
  console.log('Document inserted:', result.ops[0]);
});
 

Querying Data:

const collection = db.collection('mycollection');

// Find all documents matching a query
collection.find({ name: 'John' }).toArray((err, documents) => {
  if (err) {
    console.error('Error querying documents:', err);
    return;
  }
  console.log('Matching documents:', documents);
});
 

Updating Data:

const collection = db.collection('mycollection');

// Update a document
collection.updateOne({ name: 'John' }, { $set: { age: 31 } }, (err, result) => {
  if (err) {
    console.error('Error updating document:', err);
    return;
  }
  console.log('Document updated:', result.modifiedCount);
});
 

Deleting Data:

const collection = db.collection('mycollection');

// Delete a document
collection.deleteOne({ name: 'John' }, (err, result) => {
  if (err) {
    console.error('Error deleting document:', err);
    return;
  }
  console.log('Document deleted:', result.deletedCount);
});
 

Step 4: Handling Errors and Closing the Connection

Always handle errors and close the MongoDB connection when you're done with database operations.