{"id":3938,"date":"2023-11-04T23:13:57","date_gmt":"2023-11-04T23:13:57","guid":{"rendered":"http:\/\/localhost:10003\/how-to-use-mongodb-with-express-js\/"},"modified":"2023-11-05T05:48:26","modified_gmt":"2023-11-05T05:48:26","slug":"how-to-use-mongodb-with-express-js","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-use-mongodb-with-express-js\/","title":{"rendered":"How to Use MongoDB with Express.js"},"content":{"rendered":"
In this tutorial, we will learn how to use MongoDB with Express.js, a popular web application framework for Node.js. MongoDB is a NoSQL document database that provides high performance, scalability, and flexibility for building web applications. Combining MongoDB with Express.js allows us to easily store and retrieve data from a database in our Express.js application.<\/p>\n
Before we begin, make sure you have the following installed on your system:<\/p>\n
You can install these dependencies by following their respective installation guides.<\/p>\n
First, let’s create a new directory for our Express.js application and navigate into it:<\/p>\n
mkdir express-mongodb-app\ncd express-mongodb-app\n<\/code><\/pre>\nInitialize a new Node.js project by running the following command:<\/p>\n
npm init -y\n<\/code><\/pre>\nThis will create a package.json<\/code> file in the current directory.<\/p>\nNext, let’s install Express.js as a dependency for our project:<\/p>\n
npm install express\n<\/code><\/pre>\nNow, let’s create a new file called index.js<\/code> in our project directory. This will be the main entry point for our Express.js application.<\/p>\nOpen index.js<\/code> in a text editor and add the following code:<\/p>\nconst express = require('express');\nconst app = express();\n\napp.get('\/', (req, res) => {\n res.send('Hello World!');\n});\n\napp.listen(3000, () => {\n console.log('Server started on port 3000');\n});\n<\/code><\/pre>\nThis code sets up a basic Express.js application that listens for incoming HTTP requests on port 3000 and responds with “Hello World!” when the root URL (\/<\/code>) is accessed.<\/p>\nNow, let’s start our Express.js application by running the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nYou should see the message “Server started on port 3000” printed in the console, indicating that your Express.js application is running.<\/p>\n
Open your web browser and navigate to `http:\/\/localhost:3000`. You should see the “Hello World!” message displayed in your browser.<\/p>\n
Connecting to MongoDB<\/h2>\n
Now that we have our Express.js application up and running, let’s connect it to a MongoDB database.<\/p>\n
First, make sure you have MongoDB running on your system. You can start it by running the mongod<\/code> command in a separate terminal window:<\/p>\nmongod\n<\/code><\/pre>\nNext, let’s install the official MongoDB driver for Node.js as a dependency for our project:<\/p>\n
npm install mongodb\n<\/code><\/pre>\nNow, let’s create a new file called db.js<\/code> in our project directory. This file will contain the code for connecting to the MongoDB database.<\/p>\nOpen db.js<\/code> in a text editor and add the following code:<\/p>\nconst { MongoClient } = require('mongodb');\n\nconst url = 'mongodb:\/\/localhost:27017';\nconst dbName = 'myapp';\n\nlet client;\n\nasync function connect() {\n try {\n \/\/ Connect to MongoDB\n client = await MongoClient.connect(url, { useUnifiedTopology: true });\n\n console.log('Connected to MongoDB');\n\n \/\/ Access the database\n const db = client.db(dbName);\n\n return db;\n } catch (err) {\n console.error('Error connecting to MongoDB', err);\n throw err;\n }\n}\n\nfunction disconnect() {\n \/\/ Close the MongoDB connection\n client.close();\n\n console.log('Disconnected from MongoDB');\n}\n\nmodule.exports = {\n connect,\n disconnect,\n};\n<\/code><\/pre>\nThis code defines two functions: connect()<\/code> and disconnect()<\/code>. The connect()<\/code> function establishes a connection to the MongoDB database using the MongoClient.connect()<\/code> method. It returns the database object that we can use to interact with the database. The disconnect()<\/code> function closes the MongoDB connection.<\/p>\nNext, open index.js<\/code> in a text editor and require the db.js<\/code> file at the top of the file:<\/p>\nconst express = require('express');\nconst { connect, disconnect } = require('.\/db');\n\n...\n<\/code><\/pre>\nNow, let’s update the \/<\/code> route handler to connect to the MongoDB database and retrieve some data.<\/p>\nReplace the existing code inside the \/<\/code> route handler with the following code:<\/p>\napp.get('\/', async (req, res) => {\n try {\n \/\/ Connect to MongoDB\n const db = await connect();\n\n \/\/ Get data from the \"users\" collection\n const users = await db.collection('users').find().toArray();\n\n \/\/ Send the data as a JSON response\n res.json(users);\n\n \/\/ Disconnect from MongoDB\n disconnect();\n } catch (err) {\n console.error('Error handling request', err);\n res.status(500).send('Internal Server Error');\n }\n});\n<\/code><\/pre>\nThis code retrieves all documents from the users<\/code> collection in the MongoDB database and sends them as a JSON response.<\/p>\nNow, start your Express.js application by running the following command:<\/p>\n
node index.js\n<\/code><\/pre>\nOpen your web browser and navigate to http:\/\/localhost:3000`. You should see a JSON response containing the documents from the<\/code>users` collection in your MongoDB database.<\/p>\nInserting Data into MongoDB<\/h2>\n
Now that we are able to retrieve data from MongoDB, let’s learn how to insert data into the database.<\/p>\n
First, let’s update the \/<\/code> route handler in index.js<\/code> to insert a new document into the users<\/code> collection before retrieving the data.<\/p>\nReplace the existing code inside the \/<\/code> route handler with the following code:<\/p>\napp.get('\/', async (req, res) => {\n try {\n \/\/ Connect to MongoDB\n const db = await connect();\n\n \/\/ Insert a new document into the \"users\" collection\n await db.collection('users').insertOne({ name: 'John Doe', age: 30 });\n\n \/\/ Get data from the \"users\" collection\n const users = await db.collection('users').find().toArray();\n\n \/\/ Send the data as a JSON response\n res.json(users);\n\n \/\/ Disconnect from MongoDB\n disconnect();\n } catch (err) {\n console.error('Error handling request', err);\n res.status(500).send('Internal Server Error');\n }\n});\n<\/code><\/pre>\nThis code inserts a new document with the fields name<\/code> and age<\/code> into the users<\/code> collection before retrieving the data.<\/p>\nStart your Express.js application and open your web browser. Navigate to `http:\/\/localhost:3000` to see the updated JSON response containing the newly inserted document.<\/p>\n
Updating and Deleting Data<\/h2>\n
In addition to inserting data, MongoDB also provides methods for updating and deleting data.<\/p>\n
Let’s update our Express.js application to demonstrate how to update and delete documents in the MongoDB database.<\/p>\n
Open index.js<\/code> in a text editor and update the \/<\/code> route handler as follows:<\/p>\napp.get('\/', async (req, res) => {\n try {\n \/\/ Connect to MongoDB\n const db = await connect();\n\n \/\/ Insert a new document into the \"users\" collection\n await db.collection('users').insertOne({ name: 'John Doe', age: 30 });\n\n \/\/ Update the name of the first document in the \"users\" collection\n await db.collection('users').updateOne({}, { $set: { name: 'Jane Doe' } });\n\n \/\/ Delete the last document from the \"users\" collection\n await db.collection('users').deleteOne({});\n\n \/\/ Get data from the \"users\" collection\n const users = await db.collection('users').find().toArray();\n\n \/\/ Send the data as a JSON response\n res.json(users);\n\n \/\/ Disconnect from MongoDB\n disconnect();\n } catch (err) {\n console.error('Error handling request', err);\n res.status(500).send('Internal Server Error');\n }\n});\n<\/code><\/pre>\nThis code demonstrates how to update and delete documents in the users<\/code> collection. It updates the name of the first document to “Jane Doe” using the $set<\/code> operator and deletes the last document from the collection using the deleteOne()<\/code> method.<\/p>\nStart your Express.js application and open your web browser. Navigate to `http:\/\/localhost:3000` to see the updated JSON response containing the modified data.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, we learned how to use MongoDB with Express.js to store and retrieve data from a database in our Express.js application. We learned how to connect our application to a MongoDB database, insert data into the database, retrieve data from the database, and update and delete data in the database. MongoDB provides a simple and flexible way to persist data in our Express.js applications, allowing us to build powerful and scalable web applications.<\/p>\n
You can find the complete source code for this tutorial on GitHub<\/a>.<\/p>\nI hope you found this tutorial helpful! If you have any questions or feedback, please feel free to reach out.<\/p>\n
Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"
In this tutorial, we will learn how to use MongoDB with Express.js, a popular web application framework for Node.js. MongoDB is a NoSQL document database that provides high performance, scalability, and flexibility for building web applications. Combining MongoDB with Express.js allows us to easily store and retrieve data from a 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":[457,456,455,36,49,454],"yoast_head":"\nHow to Use MongoDB with Express.js - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n