I am creating a demo gaming web app with express and mongoose. There are several game types such as quizzes
and puzzles
.
I am trying to create one main Schema Games
, which gets inherited from other Schema game types. For example, something like this:
const quizzes = new mongoose.Schema({
question: { type: String },
answer: { type: String }
})
module.exports = mongoose.model('quiz', quizzes);
const Games = new mongoose.Schema({
// these fields apply to all games
game_name: String,
date_created: { type: Date, default: Date.now },
// game type
game_type: { type: String, enum: ['quizzes', 'puzzles', 'multiplayer'] },
game_content: { type: Object, enum: [quizzes, puzzles] }
})
module.exports = mongoose.model('games', Games);
I am effectively using quizzes as a template to be added to game_content
and stored in the db as a game. However, when I try to create a new game by doing:
const quiz = new Quiz({
question: "this is question 1",
answer: "this is answer 1"
})
const game = new Game({
game_name: "game 1",
game_type: "quizzes",
game_content: quiz
})
await game.save();
It thinks quizzes
is a real model and I get an empty quizzes table in my db along with my games table. How can I prevent this behavior?
CodePudding user response:
If you don't want to have quizzes in the database, don't create a schema for it. You can define the schema for the game content with just a nested object. Same with creating the documents.