From caa9e46694717bacabb2543fca9b062a9155303e Mon Sep 17 00:00:00 2001 From: Jweng88 <108978684+Jweng88@users.noreply.github.com> Date: Wed, 11 Sep 2024 16:42:05 +0800 Subject: [PATCH] Add question id to question schema with auto-increment --- question-service/src/model/counter-model.ts | 16 ++++++++++++++++ question-service/src/model/question-model.ts | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 question-service/src/model/counter-model.ts diff --git a/question-service/src/model/counter-model.ts b/question-service/src/model/counter-model.ts new file mode 100644 index 0000000000..4696e82faf --- /dev/null +++ b/question-service/src/model/counter-model.ts @@ -0,0 +1,16 @@ +import mongoose from "mongoose"; + +const counterSchema = new mongoose.Schema({ + _id: { + type: String, + required: true, + }, + seq: { + type: Number, + default: 0, + }, +}); + +const Counter = mongoose.model("Counter", counterSchema); + +export default Counter; diff --git a/question-service/src/model/question-model.ts b/question-service/src/model/question-model.ts index 72d5d07209..2524f86b61 100644 --- a/question-service/src/model/question-model.ts +++ b/question-service/src/model/question-model.ts @@ -7,9 +7,11 @@ // export const users: User[] = []; import mongoose, { Schema, Document } from "mongoose"; +import Counter from "./counter-model"; // Define the schema for a Question interface QuestionDocument extends Document { + question_id: number; title: string; description: string; category: string; @@ -17,10 +19,27 @@ interface QuestionDocument extends Document { } const questionSchema: Schema = new Schema({ + question_id: { type: Number, unique: true }, title: { type: String, required: true }, description: { type: String, required: true }, category: { type: String, required: true }, complexity: { type: String, required: true }, }); +// Middleware to auto-increment the question_id before saving +questionSchema.pre("save", async function (next) { + const question = this as any; + + if (question.isNew) { + const counter = await Counter.findByIdAndUpdate( + { _id: "questionId" }, + { $inc: { seq: 1 } }, + { new: true, upsert: true } + ); + question.question_id = counter?.seq; + } + + next(); +}); + export default mongoose.model("Question", questionSchema);