Open In App

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 Module

Step 1: Create a new project using the below command.

npm init -y

Step 2: Navigate to the root directory of your project:

cd <foldername>

Step 3: Install the dependency using the below command:

npm install mongodb

Project Structure:

0
Project Structure

The 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);

Explanation

  • Importing 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:

00
To make a synchronous MongoDB query in Node.js

Next Article

Similar Reads