【问题标题】:How can I use async-await with MongoClient如何将 async-await 与 MongoClient 一起使用
【发布时间】:2017-07-02 02:52:07
【问题描述】:

当我运行它时(使用 node v7.5.0 和 --harmony):

var MongoClient = require('mongodb').MongoClient,
var url = "mongodb://localhost:27017/myDB";

var test = await MongoClient.connect(url);
module.exports = test;

我收到此错误:

var test = await MongoClient.connect(url);
             ^^^^^^^^^^^
SyntaxError: Unexpected identifier

MongoClient.connect(url) 确实返回了一个承诺

我最终想要实现的是创建一个节点模块,该模块将连接到 mondoDB 并且可以在以下示例中使用:

 var db = require('../utils/db');  //<-- this is what I want to create above
 col = db.collection('myCollection');

 module.exports.create = async fuction(data) {
   return await col.insertOne(data);
 }

有什么建议吗?

【问题讨论】:

    标签: node.js mongodb async-await


    【解决方案1】:

    我是这样解决的,只打开一个连接:

    db.js

    const MongoClient = require('mongodb').MongoClient;
    
    let db;
    
    const loadDB = async () => {
        if (db) {
            return db;
        }
        try {
            const client = await MongoClient.connect('mongodb://localhost:27017/dbname');
            db = client.db('dbname');
        } catch (err) {
            Raven.captureException(err);
        }
        return db;
    };
    
    module.exports = loadDB;
    

    index.js

    const loadDB = require('./db');
    
    const db = await loadDB();
    await db.collection('some_collection').insertOne(...);
    

    【讨论】:

      【解决方案2】:

      将它包装在异步函数中怎么样?

      var MongoClient = require('mongodb').MongoClient,
      var url = "mongodb://localhost:27017/myDB";
      
      var test = async function () {
        return await MongoClient.connect(url);
      }
      
      module.exports = test;
      

      【讨论】:

      • 这里解释了如何编写模块,而不是如何使用导出的数据库连接。
      • @Carasel - 类似于const test = require('test'); const db = test();
      【解决方案3】:

      你的模块包装器也是异步函数吗?您需要将 await 关键字放在异步函数中。

      【讨论】:

      • 不!我在阅读您的回复前不久意识到。但我认为这无论如何回答了我关于“意外标识符”错误的最初问题,所以我会接受它作为正确答案。但是我仍然没有想出如何将它打包成一个模块,以便我可以从其他模块中以一种干净整洁的方式使用它。
      猜你喜欢
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 2019-04-15
      • 2014-06-19
      • 2018-01-14
      • 2018-09-12
      • 1970-01-01
      相关资源
      最近更新 更多