How to Make a Synchronous MongoDB Query in NodeJS? Last Updated : 26 Jun, 2024 Comments Improve Suggest changes Like Article Like Report MongoDB is a popular NoSQL database that is often used in modern web development. It is known for its flexibility, scalability, and ease of use. Node.js, with its non-blocking, event-driven architecture, is a natural fit for MongoDB. However, working with asynchronous code can sometimes be challenging. In this article, we'll explore how to make synchronous-like MongoDB queries in Node.js using the async and await syntax. Step to Setup a NodeJS App and Installing ModuleStep 1: Create a new project using the below command. npm init -yStep 2: Navigate to the root directory of your project: cd <foldername>Step 3: Install the dependency using the below command: npm install mongodbProject Structure:Project StructureThe Update dependencies in your package.json file will look like: "dependency":{ "mongodb": "4.1.1"}Example: The example illustrated How to make a synchronous MongoDB query in Node.js. JavaScript //index.js const { MongoClient } = require('mongodb'); async function main() { // Connection URL const url = 'mongodb://localhost:27017'; const client = new MongoClient(url, { useUnifiedTopology: true }); try { // Connect to the MongoDB server await client.connect(); console.log('Connected successfully to server'); // Select the database const db = client.db('myapp'); // Select the collection const collection = db.collection('users'); // Perform a query const query = { firstName: 'String' }; const user = await collection.findOne(query); // Print the result console.log('User:', user); } catch (err) { console.error(err); } finally { // Ensure that the client will close when you finish/error await client.close(); } } // Run the main function main().catch(console.error); ExplanationImporting MongoClient: We import the MongoClient class from the mongodb package. This class provides methods to connect to the MongoDB server and perform operations.The main function is marked as async to allow the use of await inside it.We define the MongoDB connection URL. In this example, it connects to a local MongoDB server.We create a new instance of MongoClient with the connection URL and some options.The await client.connect() line establishes the connection to the MongoDB server.We select the database and the collection we want to work with.We define a query object to find a user named "Alice".The await collection.findOne(query) line performs the query and waits for the result.Finally, we print the result to the console and close the connection in the finally block to ensure that the client is closed even if an error occurs.Output: To make a synchronous MongoDB query in Node.js Comment More infoAdvertise with us Next Article How to Make a Synchronous MongoDB Query in NodeJS? M muskangupnre1 Follow Improve Article Tags : Web Technologies Node.js MongoDB Similar Reads How to Run Synchronous Queries using sync-sql Module in Node.js ? The sync-sql module is designed to make synchronous queries to the database. Since normal SQL queries are asynchronous in node.js but if you want to run it synchronously, then it is possible using this module. In synchronized SQL, the result set is returned when the query is executed. Note: Do not u 2 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 Use MongoDB Transactions in Node.js? Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js.PrerequisitesMongoDB (Version 4.0 or higher Recommended) 2 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 MongoDB sort by relevance in Node.js ? MongoDB is a popular, open-source NoSQL database that uses a document-oriented data model. It is designed to handle large amounts of data with high performance and scalability and is often used in big data and real-time web applications. In MongoDB, data is stored in BSON (binary JSON) format, which 4 min read Like