使用express.js处理mongoose连接的正确方法是什么? [英] What's the proper way to handle mongoose connections with express.js?

查看:188
本文介绍了使用express.js处理mongoose连接的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的server.js设置,我试图运行:

I have a very simple "server.js" setup that I am trying to run:

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...');

这是设置为连接到 localhost:3000

当我导航到 localhost:3000 / first_test 时,它调用testscript中的popSingleData方法。 js:

When I navigate to localhost:3000/first_test, it calls the "popSingleData" method within testscript.js:

...
    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]));
                }
            }
        });


    });

};
...

导致问题的行是前3:

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

当在函数内部声明时,脚本按预期运行,打印出它发现的JSON对象数据库。当它们在testscript.js中定义,但在方法的范围之外时,该程序会挂起在 db.once('open',function callback(){.. 。});命令

When they are declared within the function, the script runs as expected, printing out JSON objects it found from the database. 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.

有人可以看出移动这3行代码的差异吗?每次我想要一个不同的函数访问数据库时,是否真的需要建立一个新的连接?

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?

推荐答案

如果你连接到数据库已经存在,一次事件不会再次触发。当全局连接(在函数外部)时,数据库已连接整个NodeJs进程。

If you connected to the database already, the once event won't fire again. The database was already connected for the entire NodeJs process when it was globally connected (outside of the function).

调用 mongoose.connect( 'mongodb:// localhost / test'); 使连接打开。

所以,而不是在每个函数调用中打开它(这将是一种低效的与MongoDB交互的方式) connect NodeJs应用程序启动时,并且认为连接可能不可用(因为异步)或不启动应用程序( listen ),直到连接完成(或超时)。使用Mongoose,直到连接完成,所有命令都被缓冲(但可能不是你想要的行为)。您可以使用打开事件,如果您想知道连接何时完成。

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). With Mongoose, until the connection is made, all commands are buffered (but that may not be the behavior you want). You can use the open event if you want to know when the connection is complete.

此处找到连接: mongoose.connection 如果您使用 connect 函数创建连接。

The connection is found here: mongoose.connection if you use the connect function to create the connection.

连接打开后,您可以从 popSingleData 函数中使用它,而不使用一次事件和回调。有一个连接池自动维护。

Once the connection is opened, you can use it from your popSingleData function without using the once event and callback. There's a connection pool automatically maintained.

有关连接的更多信息,请阅读这里

For more about connections, read here.

这篇关于使用express.js处理mongoose连接的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆