node.js - 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 })
);
});
为什么我收到此架构错误?
解决方案
您需要在使用之前导入模型,因此在导入 campground 模型时首先需要在 app.js 中使用模型
require('./models/Comment'); // import Comment from "./models/comment";
或者您在 campground.js 中使用的模型名称可能存在问题:
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comments", // USE "Comment"
},
推荐阅读
- python - python中random模块的randrange函数中,randrange函数中指定的上限是包含还是排除?
- c# - 在 Xamarin.Forms WebView OnBackButtonPressed 中按下后退按钮时如何检测多个实例的活动窗口
- azure-application-insights - 获取 Kusto / Application Insights 中每个 bin 的并发请求数
- python - 将 python 部署到 Heroku - Web 进程无法绑定到 $PORT
- string - VBScript 如何在字符串中包含括号
- python - 如何为使用多处理的函数设置超时?
- apache-kafka-streams - 是否可以从 Kafka 集群流式传输并发送到 Azure 事件中心
- java - 如何在 Android 中添加抽屉菜单?
- c# - 使用正则表达式格式化字符串
- numpy - numpy - 最小子数组