Reputation: 5
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;
}
}
Calling the server action from the front end:
author: userIdRef.current!,
};
const total = await getQuestionsCount(params);
console.log("Total Count", total);
working
Calling from API/route.ts
const params: GetCountByAuthorParams = { author: authorID!, };
const total = await getQuestionsCount(params);
console.log("Total Count", total);
Not working.
Upvotes: 0
Views: 84
Reputation: 5
I can able to call the server actions from route.ts after I removed the NextJS edge code or change to nodejs
export const runtime = 'nodejs' (default) | 'edge'
Upvotes: 0