9

When I run this (using node v7.5.0 with --harmony):

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

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

I get this error:

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

MongoClient.connect(url) does return a promise

What I ultimately want to achieve is to create a node module that will connect to a mondoDB and will be usable as in the following example:

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

Any suggestions?

balafi
  • 2,143
  • 3
  • 17
  • 20

3 Answers3

8

I solved it like this, only opening one connection:

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(...);
andyrandy
  • 72,880
  • 8
  • 113
  • 130
6

What about wrapping it in an async function?

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

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

module.exports = test;
spurdy
  • 61
  • 1
1

Is your module wrapper an async function as well? You need the await keyword to be in an async function.

Zlatko
  • 18,936
  • 14
  • 70
  • 123
  • No! I realized shortly before I read your reply. But I think this anyway answers my initial question about the 'unexpected identifier' error, so I will accept is as the correct answer. But I still haven't figured out how to package this into a module that I can use in a nice and clean way from other modules. – balafi Feb 14 '17 at 00:57