首页 > 解决方案 > MongooseError [MissingSchemaError]:模式尚未注册模型“评论”

问题描述

我在我的项目中使用 sucrase。当我尝试访问显示路线时,仅打印来自 Campground 模型的数据而没有任何注释,从而导致此错误。

我的show.ejs:

<%- include("partials/header") %>

<h1><%= campground.name %></h1>

<img src="<%= campground.image %> " />

<p><%= campground.description %></p>

<% campground.comments.forEach(comment => { %>
<p><strong><%= comment.author %></strong> - <%= comment.text %></p>
<% }) %> <%- include("partials/footer") %>

我的 app.js 标头:

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import Campground from "./models/campground";
import seedDB from "./seeds";

seedDB();

mongoose.connect("mongodb://localhost/yelpCamp", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const app = express();

app.use(express.static("assets"));
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");

我的campground.js:

import mongoose from "mongoose";

//* schema
const campgroundSchema = new mongoose.Schema({
  name: String,
  image: String,
  description: String,
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Comments",
    },
  ],
});

export default mongoose.model("Campground", campgroundSchema);

评论.js:

import mongoose from "mongoose";

const commentSchema = new mongoose.Schema({
  text: String,
  author: String,
});

export default mongoose.model("Comment", commentSchema);

我的演出路线:

app.get("/campgrounds/:id", (req, res) => {
  Campground.findById(req.params.id)
    .populate("comments")
    .exec((err, foundCampground) =>
      err
        ? console.log(err)
        : res.render("show", { campground: foundCampground })
    );
});

为什么我收到此架构错误?

标签: node.jsmongodbmongoose

解决方案


您需要在使用之前导入模型,因此在导入 campground 模型时首先需要在 app.js 中使用模型

require('./models/Comment'); // import Comment from "./models/comment";

或者您在 campground.js 中使用的模型名称可能存在问题:

{
  type: mongoose.Schema.Types.ObjectId,
  ref: "Comments", // USE "Comment"
},

推荐阅读