【问题标题】:Nested elements in mongoose modelling猫鼬建模中的嵌套元素
【发布时间】:2018-10-30 19:29:48
【问题描述】:

我必须以这种格式创建一个数据库:

我尝试过这样做:

var mongoose = require("mongoose")
,   Schema   = mongoose.Schema;

var categorySchema = new Schema({
    _id:              String,
    subcategory:      {
      type: Schema.Types.ObjectId,
      ref: "Subcategory"
    },
    id:               String,
    name:             String,
    page_description: String,
    page_title:       String,
    parent_category:  String,
    c_showInMenu:     Boolean
  });

module.exports = mongoose.model("Category", categorySchema);

我对每个子类别都做了同样的事情,但我将它们命名为“Subcategory”和“SubsubCategory”。我几乎是一个新手,我已经阅读了关于 mongoose 的文档,并且我还学习了一个在线课程。我觉得我知道一些东西,但我没有正确理解它或者我背后的逻辑是错误的。

另外,我已经设法在 Schemas 中找到有关递归元素的信息,但我并不完全理解它,也不知道如何在我的数据库中实现它:Recursive elements in Schema : Mongoose modelling

【问题讨论】:

  • 你想在这里达到什么目的?
  • 我正在尝试创建一个模型,以便能够在我的 ejs 文件中使用数据库中的信息。例如将其用作:

  • 根据我的观察,您已经有了数据,并且想要为其创建模型。对吗?
  • 是的,这就是我想要做的!

标签: javascript mongoose nested data-modeling


【解决方案1】:

我检查了你的代码和收藏图片。

这就是你做错了什么。

  • 您无需声明 _id 字段,它是自动生成的。
  • 保持列名与给定集合图像中的列名相同。

这应该是您的架构声明。请注意,此模式适用于整个集合,而不仅仅是类别数组。

    var mongoose = require("mongoose"),
        Schema   = mongoose.Schema;

    var mainSchema = new Schema({
        categories: [ {
        id:               String,
        image:             String,
        name:             String,
        page_description: String,
        page_title:       String,
        parent_category_id:  String,
        c_showInMenu:     Boolean
      }]
    });

这只是架构的一个示例,请对其进行必要的更改。

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2018-06-23
    • 2022-01-25
    • 1970-01-01
    • 2015-09-21
    • 2019-01-16
    • 2017-01-28
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多