在Model调用Express / Mongo Native Driver之前建立数据库连接

时间:2016-09-05 06:29:41

标签: node.js mongodb express ecmascript-6

我正在尝试为我的快速应用程序创建单例数据库连接。问题是数据库连接未在模型之前初始化。我应该在哪里调用数据库连接以及此代码有什么问题?

此外,初始化单例数据库连接的最佳方法是什么?

db.js

import Mongo from 'mongodb';
import Promise from 'bluebird';

const MongoDB = Promise.promisifyAll(Mongo);

let _database = null;

/**
 * Connect to the mongod database.
 *
 * @callback done
 * @param {string} url - MongoDB connection string
 */
export function connect(url) {
  if (_database) return;

  MongoDB.connectAsync(url)
    .then((db) => {
      _database = db;
    })
    .catch((err) => {
      console.error(`Cannot connect to MongoDB ${url} \n${err}`);
      process.exit(1);
    });
}

/**
 * Get database instance.
 *
 * @returns {Object|null}
 */
export function get() {
  return _database;
}

Location.js(型号)

import * as db from '../db';

let collection = db.get().collection('location');

class Location {

  static findAll() {
    return collection.find({}).then(cursor => cursor.toArrayAsync());
  }

}

export default Location;

index.js

import cors from 'cors';
import * as db from './db';
import logger from 'morgan';
import helmet from 'helmet';
import dotenv from 'dotenv';
import express from 'express';
import routes from './routes';
import bodyParser from 'body-parser';
import expressValidator from 'express-validator';
import * as errorHandler from './middlewares/errorHandler';

dotenv.config();
const app = express();

app.locals.title = process.env.APP_NAME;
app.locals.version = process.env.APP_VERSION;

app.use(cors());
app.use(helmet());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(expressValidator());

app.set('port', process.env.PORT || '9000');

app.use('/api', routes);

app.use(errorHandler.internalServerError);
app.use(errorHandler.notFoundError);

// Database connection
db.connect(process.env.MONGO_CONNECTION_STRING);

app.listen(app.get('port'), () => {
  console.log('Server started at http://localhost:' + app.get('port'));
});

这是我使用babel-node将代码编译到ES5时遇到的错误。 db.get()始终返回null:

server/models/Location.js:17
var collection = db.get().collection('location');
                         ^

TypeError: Cannot read property 'collection' of null

1 个答案:

答案 0 :(得分:0)

如果你只使用mongodb而不是mongoose,我认为你的语法错了。它应该是db.getCollection(" location");

来源:https://docs.mongodb.com/manual/reference/method/db.getCollection/