Skip to content

Commit

Permalink
Add question id to question schema with auto-increment
Browse files Browse the repository at this point in the history
  • Loading branch information
Jweng88 committed Sep 11, 2024
1 parent d4e7050 commit caa9e46
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions question-service/src/model/counter-model.ts
Original file line number Diff line number Diff line change
@@ -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;
19 changes: 19 additions & 0 deletions question-service/src/model/question-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,39 @@
// 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;
complexity: string;
}

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<QuestionDocument>("Question", questionSchema);

0 comments on commit caa9e46

Please sign in to comment.