简体   繁体   中英

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

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.

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