Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - Node.js mongodb driver async/await queries

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...