【问题标题】:How to nest schemas in mongoose?如何在猫鼬中嵌套模式?
【发布时间】:2019-06-21 14:25:27
【问题描述】:

我正在尝试使用 mongoose 嵌套模式,但我被卡住了,我真的不知道为什么。这是我得到的。

我的父架构

const Comment = require("./Comment");

const BookSchema = new Schema({
  _id: Number,
  comments: [{ comment: Comment }],
  ratings: [{ rate: Number }],
  calculatedRating: Number
});

module.exports = Book = mongoose.model("book", BookSchema);

和子架构


const CommentSchema = new Schema(
  {
    userName: String,
    rating: Number,
    body: String,
    submit_date: {
      type: Date,
      default: Date.now
    }
  },
  { _id: false }
);

module.exports = Comment = mongoose.model("comment", CommentSchema);

使用这个设置我得到一个错误:

"TypeError: Invalid schema configuration: 模型不是一个有效的类型 在路径注释处。”

我正在考虑我对这些出口做错了什么,但我不确定。

【问题讨论】:

  • 我的回答有帮助吗?你能把它标记为你问题的答案吗?

标签: javascript express mongoose


【解决方案1】:

你的 ./Comment 应该是:

const CommentSchema = new Schema(
  {
    userName: String,
    rating: Number,
    body: String,
    submit_date: {
      type: Date,
      default: Date.now
    }
  },
  { _id: false }
);

module.exports = CommentSchema;

如果您像以前那样定义为新模型,那么它将创建自己的集合,并将成为新模型而不是子文档架构。

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2019-07-20
    • 2017-06-12
    • 2015-09-21
    • 2014-06-22
    • 2015-12-18
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多