我刚刚开始使用next.js,每当我调用引用了另一个文档的API时,Mongoose都会向我抛出一个错误,指出"模式尚未为模型注册".

这是我的代码.

Models

Task.js

const mongoose = require("mongoose");

const TaskModel = () => {
  const schema = mongoose.Schema;

  const taskSchema = new schema(
    {
      taskName: {
        type: String,
        required: true,
      },
      empId: {
        type: schema.Types.ObjectId,
        ref: "Employee",
        required: true,
      },
      adminId: {
        type: schema.Types.ObjectId,
        ref: "Admin",
        required: true,
      },
      deptId: {
        type: schema.Types.ObjectId,
        ref: "Department",
        required: true,
      },
      deadline: {
        type: String,
      },
      status: {
        type: Boolean,
        default: false,
      },
      completedDate: {
        type: String,
        default: "",
      },
      completionStatus: {
        type: String,
        default: "Assigned",
      },
    },
    { timestamps: true }
  );

  return mongoose.models.Task ?? mongoose.model("Task", taskSchema);
};

export default TaskModel;

employee.js

const mongoose = require("mongoose");

const EmployeeModel = () => {
  const schema = mongoose.Schema;

  const employeeSchema = new schema({
    empName: {
      type: String,
      required: true,
    },
    empEmail: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    department: {
      type: schema.Types.ObjectId,
      ref: "Department",
      required: true,
      // type:String
    },
    document: {
      type: String,
    },
    loginStatus: {
      type: Boolean,
      default: false,
    },
  });

  return mongoose.models.Employee ?? mongoose.model("Employee", employeeSchema);
};

export default EmployeeModel;

db.js(用于连接应用程序和MongoDB)

import mongoose from "mongoose";

import TestModel from "@/models/test";
import TaskModel from "@/models/task";
import AdminModel from "@/models/admin";
import EmployeeModel from "@/models/employee";
import DepartmentModel from "@/models/department";

if (mongoose.connection.readyState !== 1) {
  mongoose.connect(process.env.MONGO_URI);
}
mongoose.Promise = global.Promise;

export const db = {
  Test: TestModel,
  Task: TaskModel,
  Admin: AdminModel,
  Employee: EmployeeModel,
  Department: DepartmentModel,
};

getTask/route.jsx

import { db } from "@/helpers/db";

const Task = db.Task();
export const GET = async () => {
  try {
    const result = await Task.find().populate("empId");
    return Response.json(result);
  } catch (error) {
    console.log(error);
    return Response.json(error, { status: 422 });
  }
};

dashboard/page.jsx

"use client";
import style from "./page.module.css";
import Api from "./api";
import { useState, useEffect } from "react";

const Dashboard = () => {
  const [filterData, setFilterData] = useState("");
  const [finalData, setFinalData] = useState([]);
  useEffect(() => {
    const apiCall = async () => {
      const taskdata = await fetch("http://localhost:3000/api/task/getTask");
      const actualTaskData = await taskdata.json();
      console.log(actualTaskData);
      return actualTaskData;
    };
    const apires = apiCall();
    setFinalData(apires);
  }, []);
  return (
    <div style={{ margin: 0, padding: 0 }}>
      
    </div>
  );
};

export default Dashboard;

Here is the image of my error here is the image of my error

我附上文件夹 struct 以供参考

enter image description here

推荐答案

看起来您必须注册Employee模型才能在populate方法中使用它.这是未经测试的,但请try :

const Task = db.Task();
const Employee = db.Employee(); //< Instantiate an Employee model
export const GET = async () => {
  try {
    const result = await Task.find().populate({ path: "empId", model: Employee });//< Explicitly use the Employee model here
    return Response.json(result);
  } catch (error) {
    console.log(error);
    return Response.json(error, { status: 422 });
  }
};

Mongodb相关问答推荐

Mongo 聚合查找 $gte 6 个月前的日期,以DD-MM-YYYY格式存储为字符串

Mongo 聚合将 $sort 与 $geoNear 结合使用

MongoDB:从开始日期和结束日期数组中匹配特定日期的聚合查询

从 MongoDB 中的聚合结果中获取不同的值

有谁知道这个错误的修复方法(TypeError: Cannot assign to read only property ‘map’ of object '#')

从 PHP 打印 MongoDB 日期

使用 Spring Boot >= 2.0.1.RELEASE 将 ZonedDateTime 保存到 MongoDB 时出现 CodecConfigurationException

oplog 在独立 mongod 上启用,不适用于副本集

Node.js 数据库的抽象层

什么是 Mongoose (Nodejs) 复数规则?

如何在 MongoDb 中使用杰克逊将日期字段存储为 ISODate()

mongodump 是否锁定数据库?

Node.js 和 Passport 对象没有方法 validPassword

将数据插入 MongoDB - 没有错误,没有插入

Mongoose 的保存回调是如何工作的?

具有简单密码认证的 MongoDB 副本集

mongoose中的 Date.now() 和 Date.now 有什么区别?

show dbs 给出Not Authorized to execute command错误

是否可以使用聚合框架对 MongoDB 中的 2 个字段求和?

将 FilterDefinition 转换为可以在 mongo shell 中运行的常规 json mongo 查询