访问Mongodb' db'在路由器中,NodeJS / Express

时间:2017-01-28 15:07:19

标签: node.js mongodb

我无法导出db对象以便在我的路由器(控制器)中使用。继承我连接数据库并尝试导出数据库对象的文件:

var MongoClient = require('mongodb').MongoClient
, assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/database';

// Use connect method to connect to the server
var database;

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  database =  db;
  module.exports = database;
});

我在其中一个路由器中尝试使用它:

var db = require('../path/to/file/above');

// Redirect to application
router.get('/', function(req, res, next) {
    try {
        db.close();
    } catch (err) {
        console.log(err);
    }
    res.render('index',{});
});

"的console.log(ERR)"说" db.close()不是函数"。

问:如何正确导出数据库对象,以便我可以在路由器中使用它?

3 个答案:

答案 0 :(得分:0)

我认为你的module.exports有一些问题试试这个

    var MongoClient = require('mongodb').MongoClient
    , assert = require('assert');

    // Connection URL
    var url = 'mongodb://localhost:27017/database';

    // Use connect method to connect to the server
    var database;

    function connectMongo(cb){
        MongoClient.connect(url, function(err, db) {
          assert.equal(null, err);
          console.log("Connected successfully to server");

          cb(db);
        });
    }

    module.exports = connectMongo;

答案 1 :(得分:0)

您可以使用mongoskin访问mongodb并导出db对象。

e.g。

var mongo = require('mongoskin');
var url = 'mongodb://localhost:27017/database';

var db = mongo.db(url, {native_parser:true});

module.exports = db;

并且,在您的路由器中,

var db = require('../path/to/file/above');

// Redirect to application
router.get('/', function(req, res, next) {
  try {
    //some db operations
  } catch (err) {
    console.log(err);
  }
  res.render('index',{});
});

其他解决方案是按照@Asif。

的建议传递回调

答案 2 :(得分:0)

这就是我的数据库文件(database.js)最终:

class Person(models.Model):

    FT = "Full-Time"
    PT = "Part-Time"
    C = "Contract"
    Z = "Zero hours"

    CONTRACT_CHOICES = (
    (FT, "Full-Time"),
    (PT, "Part-Time"),
    (C, "Contract"),
    (Z, "Zero hours"),
    )

    Y = "Yes"
    N = "No"

    IS_COACH_CHOICES = (
    (Y, "Person is a coach"),
    (N, "Person is NOT a coach"),
    )


    first_name = models.CharField(max_length=15, default='')
    surname = models.CharField(max_length=30, default='')
    initials = models.CharField(max_length=5, default='', null=True, blank=True)
    email = models.EmailField(default='', null=True, blank=True)
    coach_id = models.IntegerField(null=True)
    assign_as_coach = models.CharField(null=True, blank=True, choices=IS_COACH_CHOICES, default="Person is NOT a coach", max_length=5)
    position = models.CharField(max_length=30, default='', null=True, blank=True)
    contract_type = models.CharField(max_length=30, default='FT', choices=CONTRACT_CHOICES)
    user_name_check = models.CharField(max_length=30, default='', null=True, blank=True)
    def __unicode__ (self):
        return self.surname + ', ' + self.first_name

并像这样使用它(注意你必须在router.get()中调用get函数,例如,直接调用它将无法工作,因为连接尚未打开):

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var express = require('express');
var app = express();

// Connection URL
var url = 'mongodb://localhost:27017/database';

// Use connect method to connect to the server
var database;

MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    database = db;
});

// Returns DB object when called
module.exports.get = function() {
    return database;
}