Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 448
Raven Dreamer Avatar asked Aug 15 '13 18:08

Raven Dreamer


People also ask

How does Mongoose connection work?

Mongoose will try to connect with the MongoClient internally and return the instance of mongoose. this is the internal process of "conn. openUri" function and mongoose will execute the function. you can also connect the mongoClient directly without using mongoose.

Which method is used to connect to the MongoDB instance using Mongoose?

You can connect to MongoDB with the mongoose. connect() method. mongoose. connect('mongodb://localhost:27017/myapp');

Is it mandatory to use Mongoose with Node application?

It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.


1 Answers

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.

like image 114
WiredPrairie Avatar answered Oct 15 '22 21:10

WiredPrairie