Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Currently I have this code for my connection mongoose.js:

var mongoose = require('mongoose');
var uriUtil = require('mongodb-uri');
var mongodbUri = 'mongodb://localhost/db_name';
var mongooseUri = uriUtil.formatMongoose(mongodbUri);
mongoose.connect(mongooseUri);
module.exports = mongoose;

File that requires the connection is test.js:

var mongoose = require('../model/mongoose');
var schema = mongoose.Schema({...});


How can I update mongoose.js to use multiple connections with mongoose.createConnection(...) function?

I start with changes only for one connection when I do changes like that:

var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/db_name');
mongoose.open('localhost');
module.exports = mongoose;

I get "undefined is not a function". If I use this code:

var mongoose = require('mongoose');
db = mongoose.createConnection('mongodb://localhost/db_name');
db.open('localhost');
module.exports = mongoose;

I get "Error: Trying to open unclosed connection"

Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
511 views
Welcome To Ask or Share your Answers For Others

1 Answer

Mongoose handling connections via connections pool http://mongoosejs.com/docs/connections.html

You can use server: {poolSize: 5} option for increase/decrease pool (number of parallel connections)

If you need connections to different databases look here Mongoose and multiple database in single node.js project

Example of multiple connections:

var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
var Schema = new mongoose.Schema({})
var model1 = conn.model('User', Schema);
var model2 = conn2.model('Item', Schema);
model1.find({}, function() {
   console.log("this will print out last");
});
model2.find({}, function() {
   console.log("this will print out first");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...