首页 > 解决方案 > 使用 Fastify 的 Mongoose 多连接

问题描述

我正在尝试在使用 mongoose 的 fastify 中使用多个数据库连接。

对于单个数据库代码看起来像

const mongoose = require('mongoose');
const fastifyPlugin = require('fastify-plugin')
mongoose.Promise = Promise; // Set mongoose to use ES6 Promises.
const reconnectTimeout = 5000; // ms.
const db = mongoose.connection;

async function dbConnector1(fastify, options) {
    const conn1 = mongoose.connect("mongodb://localhost/db1", {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        retryWrites: false
    })
        .then(() => console.log( 'Connection to DB1 successful'))
        .catch((err) => console.error(err));
};

module.exports = fastifyPlugin(dbConnector1,{
    name: 'DB1'
})

我已将上述代码放入 conn1.js 我在 conn2.js 和 index.js 中创建了与不同 db 的类似连接我正在注册 db 插件,如下所示

        await fastify.register(require('./src/db/conn1'))
        await fastify.register(require('./src/db/conn2'))

我收到以下错误 -

MongooseError:无法调用openUri()具有不同连接字符串的活动连接。确保您没有mongoose.connect()多次调用。请参阅:https ://mongoosejs.com/docs/connections.html#multiple_connections

在此处输入图像描述

标签: node.jsmongoosefastify

解决方案


推荐阅读