简体   繁体   English

使用express.js处理猫鼬连接的正确方法是什么?

[英]What's the proper way to handle mongoose connections with express.js?

I have a very simple "server.js" setup that I am trying to run: 我有一个非常简单的“server.js”设置,我正在尝试运行:

var express = require('express'),
    wines = require('./routes/testscripts');

var app = express();

app.get('/first_test', wines.popSingleData);

app.listen(3000);
console.log('Listening on port 3000...');

This is set up to connect to localhost:3000 这设置为连接到localhost:3000

When I navigate to localhost:3000/first_test , it calls the "popSingleData" method within testscript.js: 当我导航到localhost:3000/first_test ,它调用了testscript.js中的“popSingleData”方法:

...
    var mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost/test');

    var db = mongoose.connection;

    console.log('include called');

exports.popSingleData = function(req, res) {

//  var mongoose = require('mongoose');

//  mongoose.connect('mongodb://localhost/test');

//  var db = mongoose.connection;

    console.log('function called');

    db.on('error', console.error.bind(console, 'connection error:'));
    console.log('error handler set');
    db.once('open', function callback () {
        //yay!
        console.log("DB Opened");

        var someSchema = require('../models/someSchema');

        someSchema.find(function (err, found){
            if (err) 
            {
                console.log('err');
            }

            if(found.length != 0) 
            {
                console.log("Found Data:");
                console.log(found);
                for( var i = 0; i < found.length; i++)
                {
                    res.jsonp((found[i]));
                }
            }
        });


    });

};
...

The lines that are causing issue are the first 3: 导致问题的行是前3行:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

When they are declared within the function, the script runs as expected, printing out JSON objects it found from the database. 在函数内声明它们时,脚本按预期运行,打印出从数据库中找到的JSON对象。 When they are defined within testscript.js, but outside the scope of the method , the program hangs on the db.once('open', function callback () {...}); command 当它们在testscript.js中定义,但在方法范围之外时 ,程序挂起在db.once('open', function callback () {...}); command db.once('open', function callback () {...}); command . db.once('open', function callback () {...}); command

Could someone shed some light on the difference that occurs from moving these 3 lines of code? 有人可以了解移动这三行代码所带来的差异吗? Do I really need to make a new connection every time I want a different function to access the database? 每次我想要一个不同的函数来访问数据库时,我真的需要建立一个新的连接吗?

If you connected to the database already, the once event won't fire again. 如果您已连接到数据库,则不会再次触发once事件。 The database was already connected for the entire NodeJs process when it was globally connected (outside of the function). 当数据库全局连接(在函数外部)时,数据库已连接整个NodeJs进程。

The call to mongoose.connect('mongodb://localhost/test'); mongoose.connect('mongodb://localhost/test');的调用mongoose.connect('mongodb://localhost/test'); makes the connection and opens it. 建立连接并打开它。

So, instead of opening it on each function call (which would be an inefficient way to interact with MongoDB) connect right away when the NodeJs app is started, and consider that there will be a period where the connection may not be available (as it's async), or don't start the app ( listen ) until the connection is complete (or with a timeout). 因此,不是在每个函数调用上打开它(这将是一种与MongoDB交互的低效方式),而是在启动NodeJs应用程序时立即connect ,并考虑将存在连接可能不可用的时间段(因为它是异步),或者在连接完成(或超时)之前不启动应用程序( listen )。 With Mongoose, until the connection is made, all commands are buffered (but that may not be the behavior you want). 使用Mongoose,直到建立连接,所有命令都被缓冲(但这可能不是您想要的行为)。 You can use the open event if you want to know when the connection is complete. 如果您想知道连接何时完成,可以使用open事件。

The connection is found here: mongoose.connection if you use the connect function to create the connection. 可在此处找到连接:如果使用connect函数创建连接,则为mongoose.connection

Once the connection is opened, you can use it from your popSingleData function without using the once event and callback. 打开连接后,您可以从popSingleData函数中使用它,而无需使用once事件和回调。 There's a connection pool automatically maintained. 有自动维护的连接池。

For more about connections, read here . 有关连接的更多信息,请阅读此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM