好吧,我陷入了一些技术问题,让我来解释一下。
我有一个名为Company的数据库,其中有两列name和DBname,我有多个Companies数据库,现在我想基于Company DB调用公司数据。
我已经在我的主要index.js 中连接了这样的公司数据库
const connect = mongoose.connect( 'mongodb://localhost/Company',
{
useNewUrlParser: true, useUnifiedTopology: true,
useCreateIndex: true, useFindAndModify: false
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
但当用户基于用户公司数据库登录时,我必须更改此连接
为此,我使用了像这样的DB中间件
const mongoose = require("mongoose");
let DB = (req, res, next) => {
const connect = mongoose.createConnection( 'mongodb://localhost/company_ABC',
{
useNewUrlParser: true, useUnifiedTopology: true,
useCreateIndex: true, useFindAndModify: false
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
next();
};
module.exports = { DB };
像这样,它不起作用,请帮助我解决这个问题,并提前感谢
删除连接字符串后的DB名称。
const connect = mongoose.connect( 'mongodb://localhost/',
{
useNewUrlParser: true, useUnifiedTopology: true,
useCreateIndex: true, useFindAndModify: false
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
在模式文件中选择数据库,并将其导出
const mongoose = require('mongoose')
const db = mongoose.connection.useDb("company")
const collection = db.model('collectionName', collectionSchema);
module.exports = { collection };
const { collection } = require('path-to-schema');
const files = await collection.find({})......