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

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

问题描述

我有一个使用mongodb本机驱动程序的node.js应用程序。
在使用节点v8.9.1将我的应用程序代码迁移到async / await的过程中,我很难为mongodb查询找到一种优雅的方法。
mongodb驱动程序的主要问题是,所有查询都使用回调,其中promises函数对于异步方法是必需的。

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并完全承诺,但SSL连接到mongodb的错误和糟糕的文档 - 吸引了我从这个解决方案。

  • 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?

推荐答案

这是我发现的与Mongo3和async / await兼容的最小代码片段。
享受!

This is the smallest piece of code I found that is compatible with Mongo3 and async/await. Enjoy!

module.exports = {
  myFunction: async (query) => {
    let db, client;
    try {
      client = await MongoClient.connect(process.env.MONGODB_CONNECTION_STRING, { useNewUrlParser: true });
      db = client.db(dbName);
      return await db.collection(collectionName).find(query).toArray();
    } finally {
      client.close();
    }
  }
}

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

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