You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

解决方案

情况1:同一数据库下使用不同集合存储问题

如果只是在同一个MongoDB数据库中,将不同类型的问题存入不同集合(比如mathQuestions、englishQuestions),可以通过导出动态创建模型的函数实现:

修改模型文件(如questionModel.js)

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

// 导出创建模型的函数,参数为集合名称
module.exports = function createQuestionModel(collectionName) {
  // 避免重复创建模型
  if (mongoose.models[collectionName]) {
    return mongoose.models[collectionName];
  }
  return mongoose.model(collectionName, questionSchema);
};

在控制器文件中使用

比如questionController.js中,可按需指定集合名:

const createQuestionModel = require('./questionModel');

// 创建对应集合的模型
const MathQuestion = createQuestionModel('mathQuestions');
const EnglishQuestion = createQuestionModel('englishQuestions');

// 向数学题集合插入数据示例
async function addMathQuestion(req, res) {
  try {
    const newQuestion = new MathQuestion({
      title: 'What is 2+2?',
      answers: ['3', '4', '5'],
      correctAnswer: '4'
    });
    await newQuestion.save();
    res.status(201).json(newQuestion);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
}

// 向英语题集合插入数据示例
async function addEnglishQuestion(req, res) {
  try {
    const newQuestion = new EnglishQuestion({
      title: 'What is the past tense of "go"?',
      answers: ['go', 'went', 'gone'],
      correctAnswer: 'went'
    });
    await newQuestion.save();
    res.status(201).json(newQuestion);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
}

module.exports = { addMathQuestion, addEnglishQuestion };

情况2:存入完全不同的MongoDB数据库

如果需要将问题存入独立的MongoDB数据库(比如mathDB、englishDB),需要先建立对应数据库的连接,再在该连接上创建模型:

修改模型文件

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

// 导出基于指定数据库连接创建模型的函数
module.exports = function createQuestionModelForDB(dbUrl, collectionName = 'questions') {
  // 创建目标数据库的连接
  const dbConnection = mongoose.createConnection(dbUrl);
  // 避免重复创建模型
  if (dbConnection.models[collectionName]) {
    return dbConnection.models[collectionName];
  }
  return dbConnection.model(collectionName, questionSchema);
};

在控制器文件中使用

const createQuestionModelForDB = require('./questionModel');

// 连接对应数据库并创建模型
const MathQuestion = createQuestionModelForDB('mongodb://localhost:27017/mathDB');
const EnglishQuestion = createQuestionModelForDB('mongodb://localhost:27017/englishDB');

// 向mathDB插入数据示例
async function addMathQuestion(req, res) {
  try {
    const newQuestion = new MathQuestion({
      title: 'What is 3*5?',
      answers: ['12', '15', '18'],
      correctAnswer: '15'
    });
    await newQuestion.save();
    res.status(201).json(newQuestion);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
}

// 向englishDB插入数据示例
async function addEnglishQuestion(req, res) {
  try {
    const newQuestion = new EnglishQuestion({
      title: 'What is the plural of "child"?',
      answers: ['childs', 'children', 'childrens'],
      correctAnswer: 'children'
    });
    await newQuestion.save();
    res.status(201).json(newQuestion);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
}

module.exports = { addMathQuestion, addEnglishQuestion };

注意事项

  • 不同数据库场景下,建议统一管理连接实例,避免重复创建连接造成资源浪费。
  • 字段的unique约束仅作用于单个集合,不同集合/数据库之间互不影响。

内容的提问来源于stack exchange,提问作者user21903805

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:55:28