简体   繁体   中英

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:

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

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


    });

};
...

The lines that are causing issue are the first 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. 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 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. The database was already connected for the entire NodeJs process when it was globally connected (outside of the function).

The call to 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). 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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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