codecowboy
codecowboy

Reputation: 10095

How can I reuse an open mongoose connection?

I'd like to make a simple mongoose connection and reuse the same connection to insert multiple instances of a model. Can I do this or do I need to create multiple connections? I get the following error:

Error: Trying to open unclosed connection.
    at NativeConnection.Connection.open (/Users/me/Development/Node/tennistracker/node_modules/mongoose/lib/connection.js:210:15)

Code:

function(err, resp, body) {

            var db  = mongoose.connect('mongodb://localhost/forumposts');
            var MTF = db.model('ForumPost', ForumPost);

            $ = cheerio.load(body);
            $("[id*=post]").each(function(i, elem){

                var title =$(elem).find('a strong');
                if(!$(title).text().match(/livescores/i)) {

                    var forum = $(elem).find('td.thead > span > a').text();
                    console.log('Forum: '+normalizeWS(forum));
                    title = $(title).text();
                    utils.log('Title: '+normalizeWS(title));
                    var post = $(elem).find('div > em');
                    post = $(post).text();

                    utils.log('Post: '+normalizeWS(post));

                    var MTFPost = new MTF();

                    MTFPost.author = 'author';
                    MTFPost.forum  = normalizeWS(forum);
                    MTFPost.body   = normalizeWS(post);
                    MTFPost.title  = normalizeWS(title);

                    MTFPost.save(function (err) {
                        if(err) {
                            console.log(err);
                        }
                    });                }

            });
            callback(null, 'done', callback);
        });

Upvotes: 1

Views: 1323

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

You should have that connection at a very global level.

Mongoose implements a connection pool, so you don't need and should not be trying to establish connections in each method like this.

If you want to associate different model instances to a Schema instance, then that should not be a problem. Just declare them separately, as in.

 var User1 = mongoose.model("User1", userSchema );
 var User2 = mongoose.model("User2", userSchema );

And all will be fine.

Trust that the work has been done for you. For more information, see the Connections page in the documentation.

Upvotes: 1

Related Questions