我似乎得到了一个新的模块实例"在呼叫时需要

时间:2016-02-26 23:15:42

标签: node.js mongodb express require

我正在尝试让MongoDB与Express.js一起使用。我已经按照this文章创建了一个文件db/index.js,它提供了创建数据库连接和返回连接实例的功能。在app.js中,我首先要求该文件,然后调用其成功连接到数据库的函数connect

但是,当我稍后在另一个文件db/index.js中需要文件routes/users.js时,它返回的数据库引用是null,尽管我预计它与我在获取时的引用相同我在app.js连接了。不会require总是返回第一次调用require时返回的模块的同一个实例吗?我做错了什么?

编辑:我理解,因为调用db.connect是异步的,dbusers.js的值理论上可能在连接函数返回之前为null。但是,我已经通过测试验证,即使成功创建了连接,当我对路径 / users 发出POST请求时,db仍为null

以下是3个相关文件。

app.js (执行从这里开始)

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// configuration  environment based on process.env.NODE_ENV environment variable
var config = require('./config');
var db = require('./db');

var app = express();

var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);

// Connect to Mongo on start
db.connect(config.dbUrl, function (err) {
    if (err) {
        console.log('Unable to connect to ' + config.dbUrl);
        process.exit(1);
    } else {
        console.log('Connected to ' + config.dbUrl);
    }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/tests', express.static(__dirname + '/test'));
app.use('/lib/jasmine-core', express.static(__dirname + '/node_modules/jasmine-core/lib/jasmine-core'));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

分贝/ index.js

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

var state = {
    db: null
};

exports.connect = function (url, done) {
    if (state.db)
        return done();

    MongoClient.connect(url, function (err, db) {
        if (err)
            return done(err);
        state.db = db;
        done();
    })
}

exports.get = function () {
    return state.db;
}

exports.close = function (done) {
    console.log('db close');
    if (state.db) {
        state.db.close(function (err, result) {
            state.db = null;
            done(err);
        })
    }
}

exports.createIndexes = function () {
    if (state.db) {
        state.db.collection('events').createIndex(
                {'id': 1},
        {unique: true});
    }
}

路由/ users.js

var express = require('express');
var router = express.Router();
var db = require('../db').get();

router.post('/', function (req, res, next) {
    //
    // Problem: Every time this function is called, db is null!
    //
    var users = db.collection('users');
    var userToAdd = req.body;

    users.findOne({username: userToAdd.username}).then(function (foundUser) {
        if (foundUser.length === 0) {
            res.status(400).json({error: 'Username is already in use'});
        } else {
            // TODO: ADD USER
            res.json(foundUser);
        }
    })
    .catch(function (err) {
        console.log(err);
        res.status(500).json({error: 'Database error.'});
    });
});

module.exports = router;

2 个答案:

答案 0 :(得分:2)

为了记录,你没有收到" new"例如,以下解释将帮助您理解正在发生的事情。

请注意,在通过db.connect连接到数据库之前,您需要路由。即。

[7: "ssh-rsa" | 3: e=0x010001 | 0x101=257: n=0x00dd6a…3b45e5]

您的问题有两种解决方案。

1

重新构建你的app.js代码会解决你的问题。

Apps that require users to share personal information, such as email address and date of birth, in order to function will be rejected

2

保持你的app.js不变并在你的路线中进行更改,例如,users.js使用db如下,

//Called before db.connect is called.
//so at this point in time, your db.get will return null, make sense?
//because in your users.js your are directly calling var db = require('../db').get();
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users); 

// Connect to Mongo on start
db.connect(config.dbUrl, function (err) {
    if (err) {
        console.log('Unable to connect to ' + config.dbUrl);
        process.exit(1);
    } else {
        //after this point in execution, calling db.get will return actual db and not null.
        console.log('Connected to ' + config.dbUrl);
    }
});

我希望它有意义并且有所帮助!

答案 1 :(得分:-1)

这条线 var db = require('./db'); 声明一个仅存在于该文件范围内的新变量。当您在路由/用户文件中进行类似声明时,您将创建一个全新的db变量,这意味着从未运行connect方法,因此state属性从未更改过。