mongodb 如何在Node.js中动态设置Mongoose模型的数据库名称?

e3bfsja2  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(120)

所以我在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;

但问题是,不同的问题属于不同的数据库。因此,在这个:

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

数据库应该是变量。所以我可以使用问题模型来构建问题,但将它们发送到不同的数据库。怎么做?如果这应该是一个函数,如何在Controller文件中使用它?

nlejzf6q

nlejzf6q1#

目前还不清楚你的最终目标是什么,但你可以显式地将集合设置为mongoose.model()方法的第三个参数,并阻止mongoose从模型名称推断集合(默认行为):

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

这也可以使用变量来实现:

const collection = someFunctionToDecideCollection();

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

一个非常简单的例子来说明这是如何工作的:

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);
    }
});

相关问题