I have 3 models having this relationship:
Course ==> [Chapter] ==> Quiz
i.e., I have a Course model containing an array of ObjectId
referencing Chapter documents, and my Chapter model contains an ObjectId
referencing a Quiz document.
In my Course schema definition, I have a lastUpdated
field which stores the date at which the last modification of the course was performed.
Schemas definition are given below:
Course schema:
let courseScheme = mongoose.Schema(
{
title: { type: String, required: true },
nbChapters: { type: Number, default: 0 },
chapters: { type: [mongoose.Schema.Types.ObjectId], default: [], ref: 'Chapter' },
lastUpdated: { type: Date, default: Date.now() }, // I want this field to be updated if I create/update/delete a reference or a transitive reference of this document
}
);
Chapter schema:
let chapterScheme = mongoose.Schema(
{
chapterName: {type: String, required: true},
chapterIndex: {type: Number, required: true}, // used to sort chapters on client side (for ex: in navigation menu)
course: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Course' },
quizzId: {type: mongoose.Schema.Types.ObjectId, ref: 'Quiz'},
// some more fields
}
);
Quiz schema:
let quizScheme = mongoose.Schema(
{
questions: [
{
questionIndex: {type: Number, required: true}, // used to sort questions on client side
type: {type: String, required: true, enum: ['MultiSelect', 'Select', 'Input']},
question: {type: String, required: true}
// some more fields
},
]
}
);
I'd like to know if there's any good practice to update the lastUpdated
field in my course document, if I make a modification to any of its child (direct/indirect). For example, if I add a new quiz reference to a chapter of a given course, how would one update the lastUpdated
field of the corresponding course?
I've thought of doing the following:
PS: I'm not asking for code as an answer, just some hints about what are common good practices for this kind of operations.
I'd say you have 2 possible approaches:
Handle when updating the DB
Update the lastUpdated
field upon changes to linked schemas. You have a few approaches for this (some you have mentioned)
chapters
than update courses
Handle when querying the DB
Don't update the lastUpdated
field on the courses
collection if a change was made to another collection. Instead, keep a lastUpdated
field on all relevant collections, and choose the most recent date when querying.
Example
When you are querying your data, use a $lookup
aggregation on two collections, chapters
and courses
. On the result, chose the most recent lastUpdated
date - either from courses
or from chapters
.
Hope this helps
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加