How to Retrieve Data from MongoDB Using NodeJS? Last Updated : 23 May, 2024 Comments Improve Suggest changes Like Article Like Report MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). Mongoose moduleThis module of Node.js is used for connecting the MongoDB database as well as for manipulating the collections and databases in MongoDB. The Mongoose. connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. We can also use promises, in this method in resolving the object containing all the methods and properties required for collection manipulation and in rejecting the error that occurs during connection. PrerequisitesNode JSMongoDBMongooseApproach for Retrieve Data1. Install requires dependencies like express for creating server and mongoose for connecting ,fetching and modification in database. 2. Connect to your mongodb database using mongoose.connect() method and provide your database URL. 3. Created dummy data and create mongoose shema like GFGSchema and inset data in database when mongoose.connect() method called. 4. Create a rote called "/" which helps to retrieve data form specified database using find() method which returns array of object. Project StructureProject StructureSteps to Setup ProjectStep 1: Create a folder called Demo.mkdir DemoStep 2: Inside the root directory(Demo) initialize the app using following command.cd Demonpm init -yStep 3: Install dependencies like mogoose express by following command.npm i mongoose expressStep 4: Create server.js file inside root directory(Demo) and add the given code below.mkdir server.jsUpdated package.json look like"dependencies": { "express": "^4.19.2", "mongoose": "^8.4.0" } JavaScript //server.js //require('dotenv').config(); const express = require('express'); const mongoose = require('mongoose'); const app = express(); const port = process.env.PORT || 3000; mongoose .connect("mongodb://localhost:27017/GFGDatabase") .then((err) => { console.log("Connected to the database"); addDataToMongodb(); }); const data = [ { name: "John", class: "GFG" }, { name: "Doe", class: "GFG" }, { name: "Smith", class: "GFG" }, { name: "Peter", class: "GFG" } ] const gfgSchema = new mongoose .Schema({ name: { type: String, required: true }, class: { type: String, required: true }, }); const GFGCollection = mongoose .model("GFGCollection", gfgSchema); async function addDataToMongodb() { await GFGCollection .deleteMany(); await GFGCollection .insertMany(data); console.log("Data added to MongoDB"); } app.get('/', async (req, res) => { try { const data = await GFGCollection.find(); res.json(data); console.log(data); } catch (err) { console.log(err); res.status(500).send("Internal Server Error"); } }); app .listen(port, () => { console.log(`Server is running on port ${port}`); }); Steps to run Project:1. Navigate to root directory (Demo) and run following command.node server.js2. Open browser and type URL:localhost:3000/OutputOutput in BrowserOutput in Terminal Comment More infoAdvertise with us Next Article How to Retrieve Data from MongoDB Using NodeJS? B bishal1289be21 Follow Improve Article Tags : Web Technologies Node.js MongoDB Similar Reads How to Get Data from MongoDB using Node.js? One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi 6 min read How to Post Data in MongoDB Using NodeJS? In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple 5 min read How To Query For Documents In MongoDB Using NodeJS? MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents 4 min read How to Remove Documents using Node.js Mongoose? When working with Node.js and MongoDB, managing data involves removing documents from collections. In this article, we will explore how to remove documents using Node.js and Mongoose, a popular MongoDB library that simplifies database interactions. We'll cover the various methods provided by Mongoos 3 min read How to Connect to a MongoDB Database Using Node.js MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ 4 min read How to Perform a findOne Operation in MongoDB using Node.js? The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe 4 min read How to Handle Errors in MongoDB Operations using NodeJS? Handling errors in MongoDB operations is important for maintaining the stability and reliability of our Node.js application. Whether we're working with CRUD operations, establishing database connections, or executing complex queries, unexpected errors can arise. Without proper error handling, these 8 min read How to Perform Geospatial Queries in MongoDB using Node.js? A geospatial query involves searching for data based on geographic locations. It allows developers to identify and analyze data associated with specific coordinates or within a defined proximity of a given point. In a geospatial query, we can define a geographic shape, such as a point, line, or poly 6 min read Upload and Retrieve Image on MongoDB using Mongoose Managing images efficiently is a common requirement in modern web applications. MongoDB with Mongoose provides a great method of storing and retrieving images within your database. In this tutorial, we will demonstrate how to upload and fetch images using MongoDB and Mongoose in a Node.js applicatio 5 min read How to Connect Node.js To MongoDB Atlas Using Mongoose? MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutoria 6 min read Like