当我运行它时(使用带有 --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/