猫鼬多个连接 [英] Mongoose multiple connections
问题描述
目前,我的连接 mongoose.js 具有以下代码:
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;
需要连接的文件为 test.js :
var mongoose = require('../model/mongoose');
var schema = mongoose.Schema({...});
如何更新mongoose.js以使用mongoose.createConnection(...)函数使用多个连接?
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"
有什么建议吗?
推荐答案
通过连接池的猫鼬处理连接 http://mongoosejs.com/docs/connections.html
Mongoose handling connections via connections pool http://mongoosejs.com/docs/connections.html
您可以使用server: {poolSize: 5}
选项来增加/减少池(并行连接的数量)
You can use server: {poolSize: 5}
option for increase/decrease pool (number of parallel connections)
如果您需要连接到其他数据库,请点击此处 在单个node.js项目中的猫鼬和多个数据库
If you need connections to different databases look here Mongoose and multiple database in single node.js project
多个连接的示例:
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");
});
这篇关于猫鼬多个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!