【问题标题】:Mongoose multiple connections猫鼬多个连接
【发布时间】:2015-12-30 14:56:30
【问题描述】:

目前我有此代码用于我的连接 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(...) 函数使用多个连接?

当我进行这样的更改时,我只对一个连接进行更改:

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

我得到“未定义不是函数”。 如果我使用此代码:

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

我收到“错误:尝试打开未关闭的连接”

有什么建议吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

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

    如果您需要连接到不同的数据库,请查看此处 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");
    });
    

    【讨论】:

    • 是的,我需要多个数据库连接。我看到了这个答案,但在我的情况下它仍然不起作用。 conn 和 conn2 的示例看起来最好,但我不能将它分成两个文件。你能举个例子吗?
    • 为您添加了工作示例。是你需要的吗?
    • 如果它对任何人有帮助,仅供参考,不要像使用 connect 那样使用 mongoose.model('User', Schema) (不要使用 mongoose.model);使用 connectionname.model 如示例所示
    • TypeError: conn.model is not a function if you get this error 不要在createConnection上使用.then.catch,就像使用connect一样...
    • @AeroWang TY 在看到你的评论之前我跌跌撞撞至少 30 分钟 ?
    【解决方案2】:

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

    mongoose.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

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

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

    【讨论】:

    • 我们如何才能并行关闭这些连接?我收到错误TypeError: client.s.dbCache[name].emit is not a function
    【解决方案3】:

    config.js

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

    connection.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(自定义类)

    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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多