MissingSchemaError: Schema hasn't been registered for model "Question"

Hello, I’m new here, and its my brithday today xD

I’m facing this issue when I’m trying to popoulate questions

each module has many questions

and each question belong to one module

this is module.ts

import mongoose, { Schema, models } from "mongoose";

const moduleSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  slug: {
    type: String,
    required: true,
    unique: true,
  },
  questions: [{ type: Schema.Types.ObjectId, ref: "Question" }],
});

const Module = models.Module || mongoose.model("Module", moduleSchema);

export default Module;

and this is question.ts model:

import mongoose, { Schema, models } from "mongoose";

const questionSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    options: {
      type: [String],
      required: true,
    },
    answers: {
      type: [Number],
      required: true,
    },
    module: { type: Schema.Types.ObjectId, ref: "Module" },
  },
  { timestamps: true },
);

const Question = models.Question || mongoose.model("Question", questionSchema);

export default Question;

and this is the query:

 const fetchedModule = await Module.findOne({
      slug,
    })
      .populate("questions")
      .exec();

Please help me out, this is a project for school and I’m late :cry:

Thank you!

I understand that my reply might be delayed. I encountered a similar problem before, but I found a solution that worked for me. Instead of simply referring to the “string” (i.e “Question”) name when calling the Question model within the ref attribute of moduleSchema, try referring the Question model itself.