MongoDB 模型无法在 NextJS API 中工作,但可以从前端工作

问题描述 投票:0回答:1

如果我调用从 API 调用 MongoDB 模型但在前端运行良好的服务器操作,我会收到错误。这是错误。我做错了什么吗?

> 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 ```
> 

这是型号代码。

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;

服务器操作

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;
  }
}

从前端调用服务器动作:

      author: userIdRef.current!,
    };

    const total = await getQuestionsCount(params);
    console.log("Total Count", total);

工作

从 API/route.ts 调用

常量参数:GetCountByAuthorParams = { 作者: 作者ID!, };

const total = await getQuestionsCount(params);
console.log("Total Count", total);

不工作。

mongoose next.js server-action
1个回答
0
投票

删除 NextJS 边缘代码或更改为 Nodejs 后,我可以从 Route.ts 调用服务器操作

export const runtime = 'nodejs' (default) | 'edge'

© www.soinside.com 2019 - 2024. All rights reserved.