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