{"id":3952,"date":"2023-11-04T23:13:57","date_gmt":"2023-11-04T23:13:57","guid":{"rendered":"http:\/\/localhost:10003\/how-to-use-mongodb-atlas-with-node-js-and-express-js\/"},"modified":"2023-11-05T05:48:26","modified_gmt":"2023-11-05T05:48:26","slug":"how-to-use-mongodb-atlas-with-node-js-and-express-js","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-use-mongodb-atlas-with-node-js-and-express-js\/","title":{"rendered":"How to Use MongoDB Atlas with Node.js and Express.js"},"content":{"rendered":"
MongoDB is a popular NoSQL database that provides high performance, scalability, and flexibility to store and retrieve structured and unstructured data. MongoDB Atlas is a fully-managed cloud database service that allows you to deploy, scale, and manage MongoDB clusters with ease. In this tutorial, we will learn how to use MongoDB Atlas with Node.js and Express.js to build a RESTful API.<\/p>\n
To follow along with this tutorial, you will need the following:<\/p>\n
Before we can start using MongoDB Atlas with Node.js and Express.js, we need to create a MongoDB Atlas cluster.<\/p>\n
Click on the “Build a Cluster” button to create a new cluster.<\/p>\n<\/li>\n
Select your preferred cloud provider and region, then choose the cluster tier and additional settings according to your requirements.<\/p>\n<\/li>\n
Click on the “Create Cluster” button to start creating the cluster. It may take a few minutes for the cluster to be provisioned.<\/p>\n<\/li>\n
Once the cluster is created, click on the “Connect” button.<\/p>\n<\/li>\n
In the “Connect to Cluster” dialog, click on “Connect your application”.<\/p>\n<\/li>\n
Choose the Node.js driver version, then copy the connection string.<\/p>\n<\/li>\n<\/ol>\n
Now that we have our MongoDB Atlas cluster ready, let’s set up a Node.js and Express.js project.<\/p>\n
mkdir mongodb-atlas-nodejs-express\ncd mongodb-atlas-nodejs-express\n<\/code><\/pre>\n<\/li>\n- Initialize a new npm project by running the following command and following the prompts:\n
npm init\n<\/code><\/pre>\nThis will create a package.json<\/code> file in your project directory.<\/p>\n<\/li>\n- \n
Install the required dependencies:<\/p>\n
npm install express mongodb dotenv\n<\/code><\/pre>\n<\/li>\n<\/ol>\n\nexpress<\/code> is a fast, unopinionated, minimalist web framework for Node.js.<\/li>\nmongodb<\/code> is the official MongoDB driver for Node.js.<\/li>\ndotenv<\/code> loads environment variables from a .env<\/code> file into process.env.<\/li>\n<\/ul>\n\n- Set up the project structure:\n
touch server.js\nmkdir config models routes\ntouch config\/db.js models\/book.js routes\/book.js\n<\/code><\/pre>\n<\/li>\n- Create a
.env<\/code> file in the root of your project directory and add the MongoDB Atlas connection string:\nMONGODB_URI=<your-mongodb-atlas-connection-string>\n<\/code><\/pre>\nReplace <your-mongodb-atlas-connection-string><\/code> with the connection string you copied from MongoDB Atlas earlier.<\/p>\n<\/li>\n- \n
Open server.js<\/code> and add the following code:<\/p>\nconst express = require('express');\nconst dotenv = require('dotenv');\nconst db = require('.\/config\/db');\nconst bookRoutes = require('.\/routes\/book');\n\n\/\/ Load environment variables from .env file\ndotenv.config();\n\n\/\/ Create Express app\nconst app = express();\n\n\/\/ Connect to MongoDB\ndb.connect();\n\n\/\/ Parse JSON request bodies\napp.use(express.json());\n\n\/\/ Use book routes\napp.use('\/api\/books', bookRoutes);\n\n\/\/ Start the server\nconst port = process.env.PORT || 3000;\napp.listen(port, () => {\n console.log(`Server running on port ${port}`);\n});\n<\/code><\/pre>\n<\/li>\n- Open
config\/db.js<\/code> and add the following code:\nconst mongodb = require('mongodb');\n\nfunction connect() {\n mongodb.connect(process.env.MONGODB_URI, {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n })\n .then((client) => {\n console.log('Connected to MongoDB');\n \/\/ Do something with the MongoDB client\n })\n .catch((error) => {\n console.error('Failed to connect to MongoDB', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { connect };\n<\/code><\/pre>\n<\/li>\n- Open
models\/book.js<\/code> and add the following code:\nconst mongodb = require('mongodb');\n\nclass Book {\n constructor(title, author) {\n this.title = title;\n this.author = author;\n }\n\n static findAll() {\n const db = mongodb.connection.db;\n return db.collection('books').find().toArray();\n }\n\n static create(book) {\n const db = mongodb.connection.db;\n return db.collection('books').insertOne(book);\n }\n}\n\nmodule.exports = Book;\n<\/code><\/pre>\n<\/li>\n- Open
routes\/book.js<\/code> and add the following code:\nconst express = require('express');\nconst router = express.Router();\nconst Book = require('..\/models\/book');\n\nrouter.get('\/', async (req, res) => {\n try {\n const books = await Book.findAll();\n res.json(books);\n } catch (error) {\n res.status(500).json({ error: 'An error occurred' });\n }\n});\n\nrouter.post('\/', async (req, res) => {\n const book = new Book(req.body.title, req.body.author);\n\n try {\n const result = await Book.create(book);\n res.json(result.ops[0]);\n } catch (error) {\n res.status(500).json({ error: 'An error occurred' });\n }\n});\n\nmodule.exports = router;\n<\/code><\/pre>\n<\/li>\n<\/ol>\nTesting the API<\/h2>\n
With everything set up, we can now test the API.<\/p>\n
\n- Start the server:\n
node server.js\n<\/code><\/pre>\nYou should see the following message indicating that the server is running:<\/p>\n
Server running on port 3000\n<\/code><\/pre>\n<\/li>\n- Use a tool like cURL or Postman to make HTTP requests to the API.<\/p>\n<\/li>\n<\/ol>\n
\n- To get a list of books, send a
GET<\/code> request to `http:\/\/localhost:3000\/api\/books`.<\/li>\n- \n
To create a new book, send a POST<\/code> request to http:\/\/localhost:3000\/api\/books` with a JSON body containing the<\/code>titleand<\/code>author` properties.<\/p>\nFor example, using cURL:<\/p>\n
curl -X GET http:\/\/localhost:3000\/api\/books\n<\/code><\/pre>\ncurl -X POST -H \"Content-Type: application\/json\" -d '{\"title\":\"Book Title\",\"author\":\"Book Author\"}' http:\/\/localhost:3000\/api\/books\n<\/code><\/pre>\nYou should receive a JSON response with the list of books or the created book.<\/p>\n<\/li>\n<\/ul>\n
\n- You can also use a MongoDB client like MongoDB Compass to connect to your MongoDB Atlas cluster and view and manage the data directly.<\/li>\n<\/ol>\n
Conclusion<\/h2>\n
In this tutorial, we learned how to use MongoDB Atlas with Node.js and Express.js to build a RESTful API. We set up a MongoDB Atlas cluster, created a Node.js and Express.js project, connected to MongoDB Atlas, defined a Book model, and implemented routes to handle CRUD operations on books. Now you can leverage the power of MongoDB Atlas to store and retrieve data in your Node.js and Express.js applications.<\/p>\n","protected":false},"excerpt":{"rendered":"
MongoDB is a popular NoSQL database that provides high performance, scalability, and flexibility to store and retrieve structured and unstructured data. MongoDB Atlas is a fully-managed cloud database service that allows you to deploy, scale, and manage MongoDB clusters with ease. In this tutorial, we will learn how to use 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":[455,525,527,526,528,530,529,531,19,524],"yoast_head":"\nHow to Use MongoDB Atlas with Node.js and 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