所以我在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文件中使用它?
1条答案
按热度按时间nlejzf6q1#
目前还不清楚你的最终目标是什么,但你可以显式地将集合设置为
mongoose.model()
方法的第三个参数,并阻止mongoose从模型名称推断集合(默认行为):这也可以使用变量来实现:
一个非常简单的例子来说明这是如何工作的: