猫鼬多重连接 [英] Mongoose multiple connections

查看:31
本文介绍了猫鼬多重连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这个代码用于我的连接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"

有什么建议吗?

推荐答案

Mongoose 通过连接池处理连接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)

如果您需要连接到不同的数据库,请看这里Mongoose 和单个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆