node.js - 我如何将异步等待与 MongoClient 一起使用

标签 node.js mongodb async-await

当我运行它时(使用带有 --harmony 的 Node v7.5.0):

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

有什么建议吗?

最佳答案

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

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

关于node.js - 我如何将异步等待与 MongoClient 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215592/

相关文章:

javascript - 消息在需要所有数据之前发送,这意味着它发送了几条消息,所有消息中的数据都相同

python - 有没有一种快速/最佳的方法来获取特定键的唯一值列表?

c# - 异步发布到 Azure 队列

python - 异步初始化时将参数传递给 python 类

c# - 如果使用 ConfigureAwait(false),async/await 是否仍会死锁?

node.js - Nodejs Express 4 Multer |如果用户未经授权停止文件上传

javascript - 在 Node.js 中进行动态查询的方法

javascript - `open` 和 `error` 同时与 fs.createReadStream() 和 EISDIR

node.js - 如何查找 mongoDB 中第 n 层嵌套的对象? (单个集合、单个文档)

mongodb - 分页子文档 MongoDB