Well, i am stuck in little technical stuff let me explain.
i have one database with name of Company and in this i have two columns name and DBname and i have multiple Companies databases now i want to call company data based on Company DB.
i already have connected company databse like this in my main 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));
but i have to change this connecting when user is logged in based on user company database
for this i am using a DB middleware like this
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 };
like this and it's not working please help me to resolve this issue and thanks in advance
Remove the DB name after the connection string.
const connect = mongoose.connect( 'mongodb://localhost/', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }) .then(() => console.log('MongoDB Connected...')) .catch(err => console.log(err));
Select the database in your schema file instead and export it
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({})......
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.