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:
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?
Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.
Using async / await only We declare our promise as step 1 like before, but we then utilise await to pause execution until myPromise is resolved, before closing the mongo client and resolving the API call.
Mongoose relies on the MongoDB Node. js Driver to talk to MongoDB. You can refer to this table for up-to-date information as to which version of the MongoDB driver supports which version of MongoDB.
Since all answers are missing some bits (catch blocks, checking that client is not null
) I came with my own solution. Tested with Mongo server v4.0.7 and Node JS driver 3.2.2.
Note that the example is a console program, where we close the connection to the server in the finally
block. In a web application, the connections are reused. See Node Mongo docs. Also, the errors are logged with libraries such as Winston or Morgan and not console logged.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With