如何在MongoClient中使用async-await

9
当我运行这个命令(使用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)返回一个Promise。

我最终想要实现的是创建一个Node模块,该模块将连接到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);
 }

有什么建议吗?

3个回答

8
我这样解决了它,只打开了一个连接:
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(...);

6
将其包装在异步函数中怎么样?
var MongoClient = require('mongodb').MongoClient,
var url = "mongodb://localhost:27017/myDB";

var test = async function () {
  return await MongoClient.connect(url);
}

module.exports = test;

1
这里讲解了如何编写模块,但没有说明如何使用导出的数据库连接。 - Carasel
@Carasel - 大致上是这样的 const test = require('test'); const db = test(); - 4Z4T4R

1

你的模块包装器也是一个异步函数吗?你需要在异步函数中使用await关键字。


不!在我阅读您的回复之前不久,我已经意识到了这一点。但我认为这仍然回答了我最初关于“unexpected identifier”错误的问题,所以我将其作为正确的答案接受。 但我仍然没有弄清楚如何将其打包成一个模块,以便可以从其他模块中以漂亮和干净的方式使用。 - balafi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接