node.js 猫鼬多重连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32906467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:20:46  来源:igfitidea点击:

Mongoose multiple connections

node.jsmongodbmongoose

提问by Pumych

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

目前,我的连接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:

需要连接的文件是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?

如何更新 mongoose.js 以使用具有 mongoose.createConnection(...) 函数的多个连接?

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?

有什么建议吗?

回答by vmkcom

Mongoose handling connections via connections poolhttp://mongoosejs.com/docs/connections.html

Mongoose 通过连接池处理连接http://mongoosejs.com/docs/connections.html

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

您可以使用server: {poolSize: 5}增加/减少池的选项(并行连接数)

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

如果您需要连接到不同的数据库,请查看这里的 Mongoose 和单个 node.js 项目中的多个数据库

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

回答by Pumych

OK. With your example I found a solution that fit my needs.

好的。通过您的示例,我找到了适合我需求的解决方案。

mongoose.js

猫鼬.js

var mongoose = require('mongoose');
mongoose.main_conn = mongoose.createConnection('mongodb://localhost/main');
mongoose.admin_conn = mongoose.createConnection('mongodb://localhost/admin');
module.exports = mongoose;

content.js

内容.js

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

/// functions here
schema.statics.func_a(){...};
schema.statics.func_b(){...};

// And finaly updated only one line
//exports.Content = mongoose.model('Content', schema);
exports.Content = mongoose.main_conn.model('Content', schema);

The only thing, is it OK to add connection objects to mongoose object or may be there is more elegant solution.

唯一的问题是可以将连接对象添加到猫鼬对象中,或者可能有更优雅的解决方案。

回答by Sergio Rodrigues

config.js

配置文件

module.exports = {
    default: 'main',
    main: 'mongodb://localhost/main',
    admin: 'mongodb://localhost/admin',
};

connection.js

连接.js

const mongoose = require('mongoose');
const config = require('./config');

mongoose.Promise = global.Promise;

function createConnection(name) {
    return mongoose.createConnection(config[name]);
}

module.exports = createConnection(config[config.default]);

module.exports.on = createConnection;

model.js (custom class)

model.js(自定义类)

const connection = require('./connection');

class Model {
    constructor(name, data) {
        this.data = data;
        return this.connection().model(name, data.schema);
    }

    connection() {
        if (this.data.connection) {
            return connection.on(this.data.connection);
        }

        return connection;
    }
}

module.exports = Model;

user.js

用户.js

const Schema = require('mongoose').Schema;
const conn = require('./connection');
const Model = require('./model');

const userSchema = new Schema({
    name: String,
    email: String,
    password: String
});

// USING MONGOOSE MODEL
// default connection
const UserM1 = conn.model('User', userSchema);

// admin connection
const UserM2 = conn.on('admin').model('User', userSchema);

// USING CUSTOM MODEL
// default connection
const UserC1 = new Model('User', { 
    schema: userSchema 
});

// admin connection
const UserC2 = new Model('User', { 
    schema: userSchema, 
    connection: 'admin' 
});