Search code examples
javascriptmongodbmongoose

How can I dynamically set the database name for a Mongoose model in Node.js?


So i have a Question Model in mongoose:

const mongoose = require('mongoose');

const questionSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'Please provide a question title'],
    unique: true
  },
  answers: {
    type: Array,
    required: [true, 'Please provide answers for the question'],
    unique: true
  },
  correctAnswer: {
    type: String,
    required: [true, 'Please provide correct answer']
  },
  type: {
    type: String,
    default: 'question'
  }
});
// function createModel(databaseName) {
//   return mongoose.model(databaseName, questionSchema);
// }
const Question= mongoose.model('Database', questionSchema);
module.exports = Question;

But the problem is that diffrent questions belong to diffrent databases. So in this:

  const Question= mongoose.model(**'Database'**, questionSchema);
    module.exports = Question;

Database should be a variable. So i can use the Question Model to build question but send them to diffrent databases. How to do it? If this should be a function, how to use it in Controller file?


Solution

  • It's unclear what your end-goal is but you can explicitlly set the collection as the third parameter of the mongoose.model() method and will stop mongoose from inferring the collection from the model name (default behaviour):

    const Question = mongoose.model('Question', questionSchema, 'levelOneQuestions');
    

    This can be done using a variable as well:

    const collection = someFunctionToDecideCollection();
    
    const Question = mongoose.model('Question', questionSchema, collection);
    

    A very simple example to illustrate how this would work is:

    app.get('/user/:id/questions', async (req, res, next) => {
        try {
            const user = await User.findById(req.params.id);
            if(user.level === 1){
               const Question = mongoose.model('Question', questionSchema, 'levelOneQuestions');
               const questions = await Question.find({});
            }else{
               //...
            }
            res.status(200).json({
               questions: questions
            });
        } catch(err) {
            next(err);
        }
    });