无法将MongoDB与Node.js连接

时间:2018-10-18 20:05:48

标签: node.js mongodb


我正在使用nodejs和electronic创建一个应用程序。我想使用mongodb来存储数据和东西,但是在尝试连接mongodb时遇到了一些困难。我正在使用robomongo,我可以用它连接数据库,但是当我尝试连接js文件时出现错误。错误是:

Uncaught TypeError: mongo.open is not a function

这是我的代码:

var MongoClient = require('mongodb').MongoClient
var Server = require('mongodb').Server;

var mongo = new MongoClient(new Server('localhost', 27017));
mongo.open((err, mongo) => {
  var db = mongo.db('aab');
  console.log('Connected!');
  if(err) throw err;
  mongo.close();
});

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

没有开放。这是一个示例:

let mongoUri;
let dbName;
const collectionName = 'collection';
let mongo = {};

const setEnv = (req) => {
  mongoUri = req.env.mongoUri;
  dbName = req.env.dbName;
  if (dbName === '' || mongoUri === '') {
    console.warn('no request.env');
  }
};

const mongoDbConnection = async (req) => {
  setEnv(req);
  try {
    if ( !mongo.client || mongo.uri !== mongoUri || !mongo.client.isConnected() || !mongo.db ) {
      mongo.uri = mongoUri;
      let options = { useNewUrlParser: true };
      const c = await MongoClient.connect(mongo.uri, options);
      mongo.client = c ;
      mongo.db = await mongo.client.db(dbName);
    }
    return mongo.db;
  } catch (e) {
    throw `Mongo connection failed \n ${e}`;
  }
};

const getCollection = async (req) => {
  try {
    const db = await mongoDbConnection(req);
    console.log('collection connected');
    return await db.collection(collectionName);
  } catch (e) {
    throw e;
  }
};