Reputation: 1205
Hi guys Im having a problem with MongoDB, I do not know how to design DB to support categories & subcategories...
So Im trying to create a Quiz app, with 2 models:
Question model
Category model
This is what Im trying to accomplish, I want to build Quiz app, the Quiz app will have 3 main categories: A category, B category and C category ...
Note: I will not have more than 20 subcategories per category
And each of the categories will have their own SubCategories like this: 'A category' will contains Test1, Test2, Test3, Test4, Test5... same for 'B category' it will contain Test1, Test2, Test3, Test4....
Note: I will not have more than 3 main categories
And each of this Test1, Test2 subcategories will contain a list of questions
So I based my model like this:
Category model:
export const CategorySchema = new mongoose.Schema({
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
},
name: { type:String, required:true },
slug: String,
});
Question Model:
export const QuestionSchema = new mongoose.Schema({
question: { type:String, required:true },
options: [String],
answers: Array,
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
}
});
With one additional catch, is that I would like a Question to be a part of different SubCategories, like it can be a part of A category > Test 1, B category > Test 2, A category > Test 3, so I can reuse it between different sub categories
My question is: Is this right way to design database ? Or is there some other way
Upvotes: 0
Views: 1708
Reputation: 14287
I am using the reference that the Category and a Test together forms a tests
collection, and the second collection is the questions
. There are two models I can think of, and the choice is based upon your query and application needs.
Model 1:
tests:
id: "A-Test1"
category: "A",
test: "Test1",
name / description: "...",
questions: [ "q1", "q2", "q15", "q16", "q25", ... ]
questions:
id: "q1",
details: { question: "...", options: [...], answer: [...] }
You want to find all questions for category "A" and "Test2":
$lookup
.You want to know if a question belongs to what categories/tests:
Model 2:
tests:
id: "A-Test1"
category: "A",
test: "Test1",
name / description: "..."
questions:
id: "q1",
details: { question: "...", options: [...], answer: [...] },
tests: [ "A-Test1", "A-Test5", "C-Test2", ... ]
You want to find all questions for "A" and "Test2":
You want to know a question belongs to what categories/tests:
Upvotes: 1