{"id":4048,"date":"2023-11-04T23:14:01","date_gmt":"2023-11-04T23:14:01","guid":{"rendered":"http:\/\/localhost:10003\/how-to-implement-crud-operations-with-mongodb-and-node-js\/"},"modified":"2023-11-05T05:48:23","modified_gmt":"2023-11-05T05:48:23","slug":"how-to-implement-crud-operations-with-mongodb-and-node-js","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-implement-crud-operations-with-mongodb-and-node-js\/","title":{"rendered":"How to Implement CRUD Operations with MongoDB and Node.js"},"content":{"rendered":"
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.<\/p>\n
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:<\/p>\n
npm install mongodb\n<\/code><\/pre>\nLet’s get started by creating a new Node.js project and initializing a package.json file. Open your terminal and run the following commands:<\/p>\n
mkdir crud-with-mongodb\ncd crud-with-mongodb\nnpm init -y\n<\/code><\/pre>\nThis will create a new directory called crud-with-mongodb<\/code>, navigate into the directory, and initialize a new package.json<\/code> file with default values.<\/p>\nConnecting to MongoDB<\/h2>\n
The first step is to establish a connection to the MongoDB server. Create a new file called index.js<\/code> in the crud-with-mongodb<\/code> directory and add the following code:<\/p>\nconst { MongoClient } = require('mongodb');\n\n\/\/ Connection URI for MongoDB server\nconst uri = 'mongodb:\/\/localhost:27017';\n\n\/\/ Database name\nconst dbName = 'myDatabase';\n\n\/\/ Create a new MongoClient\nconst client = new MongoClient(uri);\n\n\/\/ Connect to the MongoDB server\nasync function connect() {\n try {\n await client.connect();\n console.log('Connected to MongoDB server');\n } catch (error) {\n console.error('Error connecting to MongoDB server', error);\n }\n}\n\n\/\/ Close the connection to the MongoDB server\nfunction close() {\n client.close();\n console.log('Connection to MongoDB server closed');\n}\n\nconnect();\n<\/code><\/pre>\nIn the above code, we imported the MongoClient<\/code> class from the mongodb<\/code> module, which is the official MongoDB Node.js driver. We also specified the connection URI for the MongoDB server, which is mongodb:\/\/localhost:27017<\/code> 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.<\/p>\nWe created a new instance of MongoClient<\/code> and called the connect()<\/code> method to establish a connection to the MongoDB server. We used the await<\/code> 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.<\/p>\nTo test the connection, open your terminal and run the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nIf 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.<\/p>\n
Creating Documents<\/h2>\n
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.<\/p>\n
Create a new function called createDocument()<\/code> in the index.js<\/code> file, as shown below:<\/p>\n\/\/ Create a document in the collection\nasync function createDocument() {\n try {\n const db = client.db(dbName);\n const collection = db.collection('users');\n\n \/\/ Document to be inserted into the collection\n const document = {\n name: 'John Doe',\n email: 'johndoe@example.com',\n age: 25,\n };\n\n \/\/ Insert the document into the collection\n const result = await collection.insertOne(document);\n console.log('Document created:', result.insertedId);\n } catch (error) {\n console.error('Error creating document:', error);\n }\n}\n\ncreateDocument();\n<\/code><\/pre>\nIn the above code, we accessed the specified database using client.db(dbName)<\/code> and created a new collection called 'users'<\/code> using db.collection('users')<\/code>. We defined a new document with the fields 'name'<\/code>, 'email'<\/code>, and 'age'<\/code>. We then used the insertOne()<\/code> method to insert the document into the collection. Like the connect()<\/code> method, the insertOne()<\/code> method returns a promise object, so we used the await<\/code> 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.<\/p>\nTo test the creation of a document, open your terminal and run the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nIf 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.<\/p>\n
Reading Documents<\/h2>\n
After creating documents, we often need to retrieve or query them from the database. Let’s learn how to read documents in the 'users'<\/code> collection.<\/p>\nCreate a new function called readDocuments()<\/code> in the index.js<\/code> file, as shown below:<\/p>\n\/\/ Read documents from the collection\nasync function readDocuments() {\n try {\n const db = client.db(dbName);\n const collection = db.collection('users');\n\n \/\/ Find all documents in the collection\n const cursor = collection.find();\n\n \/\/ Convert the cursor to an array of documents\n const documents = await cursor.toArray();\n console.log('Documents read:', documents);\n } catch (error) {\n console.error('Error reading documents:', error);\n }\n}\n\nreadDocuments();\n<\/code><\/pre>\nIn the above code, we accessed the 'users'<\/code> collection using the same method as before. We used the find()<\/code> method to retrieve all documents in the collection. The find()<\/code> method returns a cursor, which allows us to iterate over the documents. We then used the toArray()<\/code> method to convert the cursor to an array of documents. Finally, we logged the retrieved documents to the console.<\/p>\nTo test the reading of documents, open your terminal and run the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nIf the reading of documents is successful, you should see an array of documents similar to the following in the terminal:<\/p>\n
Documents read: [\n {\n _id: 61147988aac5b288f42b0e24,\n name: 'John Doe',\n email: 'johndoe@example.com',\n age: 25\n }\n]\n<\/code><\/pre>\nUpdating Documents<\/h2>\n
Now let’s learn how to update documents in the 'users'<\/code> collection.<\/p>\nCreate a new function called updateDocument()<\/code> in the index.js<\/code> file, as shown below:<\/p>\n\/\/ Update a document in the collection\nasync function updateDocument() {\n try {\n const db = client.db(dbName);\n const collection = db.collection('users');\n\n \/\/ Filter for the document to be updated\n const filter = { name: 'John Doe' };\n\n \/\/ Update the document\n const update = { $set: { age: 30 } };\n\n \/\/ Update the first matching document in the collection\n const result = await collection.updateOne(filter, update);\n console.log('Document updated:', result.modifiedCount);\n } catch (error) {\n console.error('Error updating document:', error);\n }\n}\n\nupdateDocument();\n<\/code><\/pre>\nIn the above code, we accessed the 'users'<\/code> 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'<\/code>. We defined an update object using the $set<\/code> operator to update the age field to 30. We used the updateOne()<\/code> method to update the first matching document in the collection. The updateOne()<\/code> method returns a result object, which includes the number of modified documents. Finally, we logged the number of modified documents to the console.<\/p>\nTo test the updating of a document, open your terminal and run the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nIf 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.<\/p>\n
Deleting Documents<\/h2>\n
Lastly, let’s learn how to delete documents from the 'users'<\/code> collection.<\/p>\nCreate a new function called deleteDocument()<\/code> in the index.js<\/code> file, as shown below:<\/p>\n\/\/ Delete a document from the collection\nasync function deleteDocument() {\n try {\n const db = client.db(dbName);\n const collection = db.collection('users');\n\n \/\/ Filter for the document to be deleted\n const filter = { name: 'John Doe' };\n\n \/\/ Delete the document\n const result = await collection.deleteOne(filter);\n console.log('Document deleted:', result.deletedCount);\n } catch (error) {\n console.error('Error deleting document:', error);\n }\n}\n\ndeleteDocument();\n<\/code><\/pre>\nIn the above code, we accessed the 'users'<\/code> 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'<\/code>. We used the deleteOne()<\/code> method to delete the first matching document in the collection. The deleteOne()<\/code> method returns a result object, which includes the number of deleted documents. Finally, we logged the number of deleted documents to the console.<\/p>\nTo test the deletion of a document, open your terminal and run the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nIf 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.<\/p>\n
Conclusion<\/h2>\n
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.<\/p>\n","protected":false},"excerpt":{"rendered":"
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 Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1059,1057,1056,1058,1054,1055,1053,1052],"yoast_head":"\nHow to Implement CRUD Operations with MongoDB and Node.js - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n