1

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

2
  • Is the Company's DB and company_ABC's DB under the same connection string? Commented Nov 25, 2020 at 2:02
  • yes under the same connection Commented Nov 25, 2020 at 14:55

1 Answer 1

2

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({})...... 

Sign up to request clarification or add additional context in comments.

1 Comment

as i said i have to get database name from company database and then i have to get data in this case how i will get database name from company based on userID?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.