【问题标题】:Simple explanation about how to create Relationships with Mongoose关于如何与 Mongoose 建立关系的简单说明
【发布时间】:2016-02-10 18:05:20
【问题描述】:

我是 Mongo db/Mongoose 的新手,这个问题是关于 mongoose 和集合之间的关系,我知道有很多关于如何完成这项工作的教程,但仍然无法理解一个简单的方法来完成这项工作。我有两个模型:

这是主要模型:

       'use strict';

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

                var CategorySchema = new Schema({
                    name    : String,
                    info    : String,
                    items   : [{ type: Schema.Types.ObjectId, ref: 'Item' }]
                });

                var itemsSchema = Schema({
                    name        : String,
                    description : String,
                    price       : Number
                });


        var Item  = mongoose.model('Item', itemsSchema);

        module.exports = mongoose.model('Category', CategorySchema);

我需要在类别集合中填充项目数组并创建两个集合之间的关系。

当我从邮递员发帖时,我可以看到项目数组正在创建,但我无法填充数组。

如果我确实得到了类别,这就是响应:

  [
        {
          "_id": "564120be4123198a1f93feb5",
          "name": "Classic",
          "info": "this is the info",
          "__v": 0,
          "items": []
        },
        {
          "_id": "5641220b02968e901f678ff5",
          "name": "Classic",
          "info": "this is the info",
          "__v": 0,
          "items": []
        }
      ]

这是放到 api/categories/ 的结果

     {
        "_id": "564120be4123198a1f93feb5",
        "name": "test again",
        "info": "this is the info",
        "__v": 1,
        "items": []
      }

期望的输出:

      {
        "_id": "564120be4123198a1f93feb5",
        "name": "test again",
        "info": "this is the info",
        "__v": 1,
        "items": [
          {
            "_id": "some id"
            "name": "name",
            "description": "lorem ipsup"
          },
          {
            "_id": "some id"
            "name": "name",
            "description": "lorem ipsup"
          },
          {
            "_id": "some id"
            "name": "name",
            "description": "lorem ipsup"
          },
        ]
      }

【问题讨论】:

  • 您使用什么逻辑将项目插入到类别中?
  • @KevinB 我需要能够在将来删除单个项目。
  • 您使用什么逻辑将项目插入到类别中?如果它工作正常,您应该在该数组中看到一个 id。我没有看到任何 ID。
  • @KevinB 我无法在数组中获取任何 ID。我正在关注以下文档mongoosejs.com/docs/populate.html
  • “我无法在数组中获取任何 id” 这就是我要指出的。如果数组中没有任何内容可以填充,.populate 将不会填充任何内容!目前它是空的,所以 .populate 不会改变它。要使 .populate 工作,该数组需要包含属于该类别的项目 ID。

标签: javascript json node.js mongodb mongoose


【解决方案1】:

即使你在 Category 中有引用,你也应该使用populate 方法通知 mongoose 你希望他检索引用的项目。

类似:

var Category = require('./category.model'); 
Category.find().populate("items");

如果您只想填充项目模型的一个字段,您可以将其添加到填充参数中:

Category.find().populate("items","name");

我不知道您想要实现什么,但在我看来,另一种方式可能更有益(在项目模型中引用类别)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-30
    • 2021-12-20
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多