Next.js Discord

Discord Forum

MongoDB Model issue from API/route

Unanswered
Painted Redstart posted this in #help-forum
Open in Discord
Painted RedstartOP
hi team,

I am getting an error if I call the server action that calls the MongoDB model from API but works perfectly from the front end. here is the error. Anything I am doing wrong?

 ⨯ database/question.model.ts (49:0) @ <unknown>
 ⨯ Cannot read properties of undefined (reading 'Question')
  47 | });
  48 |
> 49 | const Question = models.Question || model("Question", QuestionSchema);
  50 |
  51 | export default Question;
  52 |
 â—‹ Compiling /_error ...
 ✓ Compiled /_error 



here is the model code.

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

export interface IQuestion extends Document {
  quetions: string;
  author: Schema.Types.ObjectId[];
  answers: string;
}

const QuestionSchema = new Schema({
  questions: { type: String, required: true },
  author: { type: Schema.Types.ObjectId, ref: "User" },
  answers: { type: String, required: false },
});

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

export default Question;

server action

 
export async function getQuestionsCount(params: GetCountByAuthorParams) {
  try {
    connectToDatabase();

    const { author } = params;

    console.log("Author", author);

    const query: FilterQuery<typeof Question> = {
      author,
    };

    const totalQuestions = await Question.countDocuments(query);
    return totalQuestions;
  } catch (error) {
    console.log(error);
    throw error;
  }
}
 

0 Replies