Node.js mongodb 驱动程序异步/等待查询 [英] Node.js mongodb driver async/await queries

查看:26
本文介绍了Node.js mongodb 驱动程序异步/等待查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 mongodb 本机驱动程序的 node.js 应用程序.在使用 node v8.9.1 将我的应用程序代码迁移到 async/await 的过程中,我正在努力为 mongodb 查询找到一种优雅的方式.mongodb 驱动程序的主要问题是,所有查询都使用回调,其中异步方法必须使用 promise 函数.

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.

替代方案:

  • mongoose - 承诺查询已弃用,并强制使用 Schema 模型,这对我的应用程序来说是一个小开销.
  • mongoist - 据称很棒,因为它在构建时考虑了 async/await 并完全承诺,但是与 mongodb 的 SSL 连接错误和糟糕的文档 - 使我远离这个解决方案.
  • 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.

我以优雅的方式成功实现的唯一解决方法是使用 callback-promise npm 包将 mongodb 驱动程序 API 转换为完全承诺.

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?

推荐答案

由于所有答案都缺少一些位(catch 块,检查客户端不是 null),因此我提出了自己的解决方案.使用 Mongo 服务器 v4.0.7 和 Node JS 驱动程序 3.2.2 测试.

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.

请注意,示例是一个控制台程序,我们在 finally 块中关闭了与服务器的连接.在 Web 应用程序中,连接被重用.请参阅 Node Mongo 文档.此外,这些错误是用 Winston 或 Morgan 等库记录的,而不是控制台记录的.

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

这篇关于Node.js mongodb 驱动程序异步/等待查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆