什么'这是用express.js处理mongose连接的正确方法

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

本文关键字:连接 mongose 处理 方法 js express 什么      更新时间:2023-09-26

我尝试运行一个非常简单的"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...');

设置为连接到localhost:3000

当我导航到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]));
                }
            }
        });

    });
};
...

引起问题的线路是前3:

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

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

有人能解释一下移动这3行代码会产生什么不同吗?每次我想要一个不同的函数来访问数据库时,我真的需要建立一个新的连接吗?

如果已连接到数据库,则once事件不会再次激发。当数据库全局连接(在函数之外)时,它已经为整个NodeJ进程连接。

mongoose.connect('mongodb://localhost/test');的调用建立连接并打开它。

因此,当NodeJs应用程序启动时,不要在每次函数调用时打开它(这将是一种与MongoDB交互的低效方式)connect,并考虑到会有一段时间连接可能不可用(因为它是异步的),或者在连接完成(或超时)之前不要启动应用程序(listen)。使用Mongoose,在建立连接之前,所有命令都会被缓冲(但这可能不是您想要的行为)。如果您想知道连接何时完成,可以使用open事件。

如果使用connect函数创建连接,则可以在此处找到连接:mongoose.connection

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

有关连接的更多信息,请阅读此处。