草庐IT

javascript - express 4 router with express.Router(),如何获取全局数据库连接?

coder 2023-11-05 原文

如何将 Node 中的全局变量从文件传递到模块? 我正在尝试使用作为数据库 mongo 连接的 db 变量。我为我尝试执行的连接复制了文件的内容,但没有工作,控制台中没有错误;就在我的浏览器中出现错误 500。

应用程序.js

var express = require('express');
var accounts = require('./routes/accounts');

var app = express();
app.set('port', process.env.PORT || 3000);


app.use('/accounts', accounts);

app.use(function(req, res) {
    res.type('text/plain');
    res.status(404);
    res.send('404 - Not Found');
});

// custom 500 page
app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.type('text/plain');
    res.status(500);
    res.send('500 - Server Error');
});

var mongoUtil = require( './mongoUtil');

mongoUtil.connectToServer( function( err ) {


    app.listen(app.get('port') , function() {
        console.log('Express started in ' + app.get('env') +
            ' mode on http://localhost:' + app.get('port') +
            '; press Ctrl-C to terminate.');
    });
} );

mongoUtils.js

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

var dbclass = module.exports = {

    db : null,

    connectToServer: function( callback ) {

        var url = 'mongodb://localhost:27017/crm1';

        MongoClient.connect(url, function(err, db) {
            if(err) throw err;

            console.log("Connected successfully to server");


            dbclass.db  = db;


        });


    },

    getDb: function() {
        return dbclass.db;
    }
};

/router/accounts.js

var express = require('express');

var router = express.Router();
var db =  .... ??? ;


router.get('/', function(req, res) {
    findDocuments(db, function() {
        db.close();
    });

});

router.post('/', function(req, res) {
    res.send('POST handler for /dogs route.');
});



var findDocuments = function(db, callback) {
    // Get the documents collection
    var collection = db.collection('accounts');
    // Find some documents
    collection.find().toArray(function(err, docs) {

        console.log("Found the following records");
        console.log(docs);
        callback(docs);

    });


}

module.exports = router;

最佳答案

一个有效但并不糟糕的方法是不直接导出路由器,而是为它导出一个生成器。生成器可以使用多种语法,我选择向您展示一个使用与您用于 MongoUtils 的模式类似的模式的示例:

应用程序.js:

var express = require('express');

var app = express();
app.set('port', process.env.PORT || 3000);

var mongoUtil = require( './mongoUtil');

mongoUtil.connectToServer( function( err ) {
    var accounts = require('./routes/accounts');
    accounts.init(mongoUtils.getDb());
    app.use('/accounts', accounts.getRouter());

    app.use(function(req, res) {
        res.type('text/plain');
        res.status(404);
        res.send('404 - Not Found');
    });

    // custom 500 page
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.type('text/plain');
        res.status(500);
        res.send('500 - Server Error');
    });

    app.listen(app.get('port') , function() {
        console.log('Express started in ' + app.get('env') +
            ' mode on http://localhost:' + app.get('port') +
            '; press Ctrl-C to terminate.');
    });
} );

/router/accouts.js:

var express = require('express');
var router = express.Router();

function init(db) {
    router.get('/', function(req, res) {
        findDocuments(db, function() {
            db.close();
        });

    });

    router.post('/', function(req, res) {
        res.send('POST handler for /dogs route.');
    });

    var findDocuments = function(db, callback) {
        // Get the documents collection
        var collection = db.collection('accounts');
        // Find some documents
        collection.find().toArray(function(err, docs) {
            console.log("Found the following records");
            console.log(docs);
            callback(docs);
        });
    }
}

function getRouter() {
    return router;
}


module.exports = {
    init: init,
    getRouter: getRouter
};

关于javascript - express 4 router with express.Router(),如何获取全局数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40653599/

有关javascript - express 4 router with express.Router(),如何获取全局数据库连接?的更多相关文章

随机推荐