TypeError子类别不是构造函数

时间:2019-07-14 12:33:36

标签: node.js mongoose mongoose-schema

我正在创建有史以来最简单的架构,但是却遇到了这个令人讨厌的错误,并且不确定为什么。也许我只需要新鲜的眼睛才能看到明显的错误。我得到的错误是:

  

TypeError子类别不是构造函数

我创建了所有这样的架构,并且之前没有遇到问题。

我的猫鼬模式:

const mongoose = require("mongoose");

const subcategorySchema = new mongoose.Schema({
  name: {
    type: String,
    minlength: 5,
    maxlength: 255
  }
});

const Subcategory = mongoose.model("Subcategory", subcategorySchema);

module.exports = Subcategory;

控制器:

const { Subcategory } = require("../models/subcategoryModel");

// add subcategory
exports.postSubcategory = async (req, res) => {
  let subcategory = new Subcategory({
    name: req.body.name
  });
  subcategory = await subcategory.save();
  res.status(200).json({
    status: "success",
    data: {
      data: subcategory
    }
  });
};

路线:

const express = require("express");
const subcategoryController = require("../controllers/subcategoryController");

const router = express.Router();

router.get("/", subcategoryController.getSubcategories);
router.post("/", subcategoryController.postSubcategory);

module.exports = router;

1 个答案:

答案 0 :(得分:0)

由于您要像这样导出Subcategory

module.exports = Subcategory;

您需要将其导入,如下所示:

const Subcategory = require("../models/subcategoryModel");