最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在创建模型的NodeJS与多个JS文件子文件

运维笔记admin8浏览0评论

在创建模型的NodeJS与多个JS文件子文件

在创建模型的NodeJS与多个JS文件子文件

在项目的NodeJS,我有2款“新闻”和“评论”,如下图。

/* File: Comment.js */
const mongoose = require("mongoose");

/* Create Comment Schema */
var commentSchema = mongoose.Schema({
  text: { type: String, required: 'Kindly enter the comment text'},
  newsId: { type: mongoose.Schema.Types.ObjectId, ref: "News", required: 'Provide the news ID to which this comment belongs' },
  created_date: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Comment', commentSchema);

/* File: News.js */
const mongoose = require("mongoose");

/* Create News Schema */
var newsSchema = mongoose.Schema({
  link: { type: String, index: {unique: true, dropDups: true}, required: 'Kindly enter the link of the news' },
  description: { type: String, required: 'Kindly enter the description of the news' },
  comments: { type: [commentSchema] }
});

module.exports = mongoose.model('News', newsSchema);

新闻模型具有评论阵列是一个子文件。但它抛出错误

的ReferenceError:commentSchema没有定义。

我注意到,如果两个模式作为一个文件,它不抛出任何错误。

回答如下:

看起来你是不是在news.js进口commentSchema,这就是为什么它的工作原理时,他们都在一个文件中。

发布评论

评论列表(0)

  1. 暂无评论