How to Implement CRUD Operations with MongoDB and Node.js

In this tutorial, we will learn how to implement CRUD (Create, Read, Update, Delete) operations with MongoDB and Node.js. MongoDB is a NoSQL database that provides high performance, high availability, and easy scalability. Node.js is a popular JavaScript runtime built on Chrome’s V8 JavaScript engine, which allows us to build scalable and efficient server-side applications.

We will be using the official MongoDB Node.js driver, which provides a high-level API for interacting with MongoDB. You can install the driver using npm, the package manager for Node.js, by running the following command:

npm install mongodb

Let’s get started by creating a new Node.js project and initializing a package.json file. Open your terminal and run the following commands:

mkdir crud-with-mongodb
cd crud-with-mongodb
npm init -y

This will create a new directory called crud-with-mongodb, navigate into the directory, and initialize a new package.json file with default values.

Connecting to MongoDB

The first step is to establish a connection to the MongoDB server. Create a new file called index.js in the crud-with-mongodb directory and add the following code:

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

// Connection URI for MongoDB server
const uri = 'mongodb://localhost:27017';

// Database name
const dbName = 'myDatabase';

// Create a new MongoClient
const client = new MongoClient(uri);

// Connect to the MongoDB server
async function connect() {
  try {
    await client.connect();
    console.log('Connected to MongoDB server');
  } catch (error) {
    console.error('Error connecting to MongoDB server', error);
  }
}

// Close the connection to the MongoDB server
function close() {
  client.close();
  console.log('Connection to MongoDB server closed');
}

connect();

In the above code, we imported the MongoClient class from the mongodb module, which is the official MongoDB Node.js driver. We also specified the connection URI for the MongoDB server, which is mongodb://localhost:27017 in this case. You may need to modify this URI depending on the location and port of your MongoDB server. We also specified the name of the database that we want to connect to.

We created a new instance of MongoClient and called the connect() method to establish a connection to the MongoDB server. We used the await keyword to wait for the connection operation to complete, as it returns a promise object. If there is an error while connecting, we catch the error and log it to the console.

To test the connection, open your terminal and run the following command:

node index.js

If the connection is successful, you should see the message “Connected to MongoDB server” in the terminal. If there is an error, make sure that your MongoDB server is running and that the connection URI is correct.

Creating Documents

Now that we have established a connection to the MongoDB server, let’s learn how to create documents in a collection. A collection is a grouping of MongoDB documents, similar to a table in a relational database.

Create a new function called createDocument() in the index.js file, as shown below:

// Create a document in the collection
async function createDocument() {
  try {
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Document to be inserted into the collection
    const document = {
      name: 'John Doe',
      email: '[email protected]',
      age: 25,
    };

    // Insert the document into the collection
    const result = await collection.insertOne(document);
    console.log('Document created:', result.insertedId);
  } catch (error) {
    console.error('Error creating document:', error);
  }
}

createDocument();

In the above code, we accessed the specified database using client.db(dbName) and created a new collection called 'users' using db.collection('users'). We defined a new document with the fields 'name', 'email', and 'age'. We then used the insertOne() method to insert the document into the collection. Like the connect() method, the insertOne() method returns a promise object, so we used the await keyword to wait for the operation to complete. If there is an error during the creation of the document, we catch the error and log it to the console.

To test the creation of a document, open your terminal and run the following command:

node index.js

If the document creation is successful, you should see a message similar to “Document created: 61130a75e4b958f358a7ee2e” in the terminal, along with the unique identifier (ObjectId) of the newly created document.

Reading Documents

After creating documents, we often need to retrieve or query them from the database. Let’s learn how to read documents in the 'users' collection.

Create a new function called readDocuments() in the index.js file, as shown below:

// Read documents from the collection
async function readDocuments() {
  try {
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Find all documents in the collection
    const cursor = collection.find();

    // Convert the cursor to an array of documents
    const documents = await cursor.toArray();
    console.log('Documents read:', documents);
  } catch (error) {
    console.error('Error reading documents:', error);
  }
}

readDocuments();

In the above code, we accessed the 'users' collection using the same method as before. We used the find() method to retrieve all documents in the collection. The find() method returns a cursor, which allows us to iterate over the documents. We then used the toArray() method to convert the cursor to an array of documents. Finally, we logged the retrieved documents to the console.

To test the reading of documents, open your terminal and run the following command:

node index.js

If the reading of documents is successful, you should see an array of documents similar to the following in the terminal:

Documents read: [
  {
    _id: 61147988aac5b288f42b0e24,
    name: 'John Doe',
    email: '[email protected]',
    age: 25
  }
]

Updating Documents

Now let’s learn how to update documents in the 'users' collection.

Create a new function called updateDocument() in the index.js file, as shown below:

// Update a document in the collection
async function updateDocument() {
  try {
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Filter for the document to be updated
    const filter = { name: 'John Doe' };

    // Update the document
    const update = { $set: { age: 30 } };

    // Update the first matching document in the collection
    const result = await collection.updateOne(filter, update);
    console.log('Document updated:', result.modifiedCount);
  } catch (error) {
    console.error('Error updating document:', error);
  }
}

updateDocument();

In the above code, we accessed the 'users' collection using the same method as before. We specified a filter to find the document to be updated, in this case, the document with a name value of 'John Doe'. We defined an update object using the $set operator to update the age field to 30. We used the updateOne() method to update the first matching document in the collection. The updateOne() method returns a result object, which includes the number of modified documents. Finally, we logged the number of modified documents to the console.

To test the updating of a document, open your terminal and run the following command:

node index.js

If the updating of a document is successful, you should see a message similar to “Document updated: 1” in the terminal, indicating that one document has been modified.

Deleting Documents

Lastly, let’s learn how to delete documents from the 'users' collection.

Create a new function called deleteDocument() in the index.js file, as shown below:

// Delete a document from the collection
async function deleteDocument() {
  try {
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Filter for the document to be deleted
    const filter = { name: 'John Doe' };

    // Delete the document
    const result = await collection.deleteOne(filter);
    console.log('Document deleted:', result.deletedCount);
  } catch (error) {
    console.error('Error deleting document:', error);
  }
}

deleteDocument();

In the above code, we accessed the 'users' collection using the same method as before. We specified a filter to find the document to be deleted, in this case, the document with a name value of 'John Doe'. We used the deleteOne() method to delete the first matching document in the collection. The deleteOne() method returns a result object, which includes the number of deleted documents. Finally, we logged the number of deleted documents to the console.

To test the deletion of a document, open your terminal and run the following command:

node index.js

If the deletion of a document is successful, you should see a message similar to “Document deleted: 1” in the terminal, indicating that one document has been deleted.

Conclusion

In this tutorial, we learned how to implement CRUD operations with MongoDB and Node.js. We covered how to connect to a MongoDB server, create documents in a collection, read documents from a collection, update documents in a collection, and delete documents from a collection. We used the official MongoDB Node.js driver to interact with the MongoDB server and performed these operations asynchronously using async/await. I encourage you to continue exploring the capabilities of MongoDB and adapting these concepts to your own projects.

Related Post