MongoDB CRUD Tutorials in JavaScript/Node.js: A Step-by-Step Guide

In this tutorial, we will explore how to perform CRUD (Create, Read, Update, Delete) operations with MongoDB using JavaScript and Node.js.

Posted on

MongoDB is a powerful NoSQL database that seamlessly integrates with JavaScript and Node.js applications. In this tutorial, we will explore how to perform CRUD (Create, Read, Update, Delete) operations with MongoDB using JavaScript and Node.js. By the end of this article, you’ll have a solid understanding of how to interact with a MongoDB database from your JavaScript applications.

Prerequisites

  • Node.js installed on your machine.
  • A running MongoDB server.
  • Basic knowledge of JavaScript and Node.js.

Step 1: Install Required Packages

Before we start working with MongoDB, let’s make sure we have the necessary packages installed. We’ll use the mongodb package for connecting to the database and executing queries.

npm install mongodb

Step 2: Set Up the Database Connection

In your Node.js application, you need to establish a connection to the MongoDB database. Create a JavaScript file (e.g., db.js) and add the following code:

const { MongoClient } = require("mongodb")

const uri = "mongodb://localhost:27017" // Replace with your MongoDB connection URI
const client = new MongoClient(uri)

async function connectToDatabase() {
  try {
    await client.connect()
    console.log("Connected to MongoDB")
    return client.db("your-database-name") // Replace with your database name
  } catch (err) {
    console.error("Error connecting to MongoDB:", err)
  }
}

module.exports = connectToDatabase

Replace 'mongodb://localhost:27017' with your MongoDB connection URI and 'your-database-name' with your database name.

Step 3: Create a New Document (Create - C)

Now, let’s create a function to insert data into a MongoDB collection. Create a JavaScript file (e.g., create.js) and add the following code:

const connectToDatabase = require("./db")

async function createDocument(data) {
  const db = await connectToDatabase()
  const collection = db.collection("your-collection-name") // Replace with your collection name

  try {
    const result = await collection.insertOne(data)
    console.log(`Document inserted with ID: ${result.insertedId}`)
  } catch (err) {
    console.error("Error creating document:", err)
  } finally {
    db.close()
  }
}

const newData = {
  name: "John Doe",
  email: "[email protected]"
}

createDocument(newData)

This code defines a function createDocument that inserts a new document into a MongoDB collection.

Step 4: Read Documents (Read - R)

To read data from the database, create another JavaScript file (e.g., read.js) with the following code:

const connectToDatabase = require("./db")

async function readDocuments() {
  const db = await connectToDatabase()
  const collection = db.collection("your-collection-name") // Replace with your collection name

  try {
    const documents = await collection.find({}).toArray()
    documents.forEach((doc) => {
      console.log(
        `Document ID: ${doc._id}, Name: ${doc.name}, Email: ${doc.email}`
      )
    })
  } catch (err) {
    console.error("Error reading documents:", err)
  } finally {
    db.close()
  }
}

readDocuments()

This code defines a function readDocuments that retrieves all documents from a MongoDB collection and prints them to the console.

Step 5: Update Documents (Update - U)

To update existing documents, create a JavaScript file (e.g., update.js) with the following code:

const connectToDatabase = require("./db")

async function updateDocument(id, newData) {
  const db = await connectToDatabase()
  const collection = db.collection("your-collection-name") // Replace with your collection name

  try {
    const result = await collection.updateOne({ _id: id }, { $set: newData })
    console.log(`Document updated: ${result.modifiedCount} documents modified`)
  } catch (err) {
    console.error("Error updating document:", err)
  } finally {
    db.close()
  }
}

const documentIdToUpdate = "your-document-id" // Replace with the document ID to update
const updatedData = {
  name: "Jane Doe"
}

updateDocument(documentIdToUpdate, updatedData)

This code defines a function updateDocument that updates a document in a MongoDB collection based on its ID.

Step 6: Delete Documents (Delete - D)

To delete documents, create a JavaScript file (e.g., delete.js) with the following code:

const connectToDatabase = require("./db")

async function deleteDocument(id) {
  const db = await connectToDatabase()
  const collection = db.collection("your-collection-name") // Replace with your collection name

  try {
    const result = await collection.deleteOne({ _id: id })
    console.log(`Document deleted: ${result.deletedCount} documents deleted`)
  } catch (err) {
    console.error("Error deleting document:", err)
  } finally {
    db.close()
  }
}

const documentIdToDelete = "your-document-id" // Replace with the document ID to delete

deleteDocument(documentIdToDelete)

This code defines a function deleteDocument that deletes a document from a MongoDB collection based on its ID.

Conclusion

In this article, we’ve covered the fundamental CRUD operations using MongoDB with JavaScript and Node.js. You’ve learned how to establish a database connection, create, read, update, and delete documents. This knowledge will empower you to build more complex applications that interact with MongoDB databases seamlessly. Remember to handle errors gracefully and adapt these examples to suit your specific project requirements.