Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (4k points)

I have a node.js application using mongodb native driver. In the process of migrating my application code to async/await using node v8.9.1, I am struggling to find an elegant way for the mongodb queries. The major problem with mongodb driver is, that all queries are using callbacks where promises functions are mandatory for the async methods.

Alternatives:

  • mongoose- promises queries deprecated and it forces using Schema model which is a little overhead for my app.
  • mongoist- allegedly great, since it built with async/await in mind and fully promise, but errors with SSL connection to mongodb and poor documentations- drew me away from this solution.

The only workaround I succeeded to implement in an elegant way is using callback-promise npm package to convert mongodb driver API to fully promise.

Any fresh ideas for an elegant high performance way?

1 Answer

0 votes
by (8.7k points)
edited by

Refer to the below MongoDB to understand about it:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017';

async function findOne() {

    const client = await MongoClient.connect(url, { useNewUrlParser: true })

        .catch(err => { console.log(err); });

    if (!client) {

        return;

    }

    try {

        const db = client.db("testdb");

        let collection = db.collection('cars');

        let query = { name: 'Volkswagen' }

        let res = await collection.findOne(query);

        console.log(res);

    } catch (err) {

        console.log(err);

    } finally {

        client.close();

    }

}

await findOne();

Go through Intellipaat’s Web Development Course and enroll today to acquire skills in Web Develpment! 

Related questions

0 votes
0 answers
asked Mar 3, 2021 in Web Technology by adhiraj (4k points)
0 votes
1 answer
asked Feb 19, 2021 in Web Technology by adhiraj (4k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...