node.js - 使用 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
解决方案
推荐阅读
- flutter - Flutter - 在执行 .then 之前,函数返回值,然后读取 .then
- python - 如何从位于3索引倍数的列表中获取所有数字
- python - 使用xpath selenium python获取子元素
- c# - 如何在通用存储库中的 linq 中添加包含属性的位置?
- ios - cordova-plugin-local-notification 触发器在 IOS 中不起作用
- java - 递归:最长回文子串
- c++ - 如何从 C++ 中的二进制文件中读取字符串?
- awk - 仅使用 grep 返回匹配模式 aginst 文件
- javascript - 使用 RPC 发送电子邮件 RegEx Javascript
- ios - SwiftUI - 如何将 aspectFit 应用于图像,使其不会超出指定区域