【问题标题】:Mongoose - Child Schema References Parent SubdocumentMongoose - 子架构引用父子文档
【发布时间】:2016-02-29 13:06:38
【问题描述】:

是否有可能拥有类似于以下内容的 Mongoose Schema:

var categorySchema = new Schema({
    name : String
});

var childSchema = new Schema({
   name : String,
   category : {
      type : Schema.Types.ObjectId,
      ref : 'parent.categories'
   }
});

var parentSchema = new Schema({
    categories : [categorySchema],
    children : [childSchema]
});

基本上,子级只能拥有其父级所包含的类别。我正在尝试做的事情可能吗?如果不是,那么最干净的方法是什么?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    如果categorySchema中只有一个字段name,也许你可以把它放在parentSchema中而不用population,如下所示,

    var childSchema = new Schema({
       name : String,
       category : {
          name: String
       }
    });
    
    var parentSchema = new Schema({
        categories : [{name: String}],
        children : [childSchema]
    });
    

    当尝试将新的child插入parent时,您可以先查询parent,然后迭代categories以获取现有的并将其添加到children,最后保存parent,示例代码如下

    Parent.find({_id: parent._id})
          .exec(function(err, p) {
              if (err) throw err;
              var p = new Child({name: 'tt'});
              p.categories.forEach(function(c) {
                  if (c /*find the match one*/) {
                      p.category = c; // assign the existing category to children
                  }
              });
              // save this parent
              p.save(function(err) {...});
          });  
    

    如果categorySchema 中有很多字段,也许将其定义为单独的架构可能是一种选择,以防Parent 中有很多类别而使父集合太大。

    var categorySchema = new Schema({
        name : String,
        // other fields....
    });
    var Category = mongoose.model('Category', categorySchema);
    
    var childSchema = new Schema({
       name : String,
       category : {type : Schema.Types.ObjectId, ref : 'Category'}
    });
    
    var parentSchema = new Schema({
        categories : [{type : Schema.Types.ObjectId, ref : 'Category'}],
        children : [childSchema]
    });
    

    尝试将新的children 添加到parent 文档时的逻辑与上述相同。

    【讨论】:

    • 我希望 mongoose 有一些神奇的方法可以隐含地做到这一点,但这很简单,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2015-04-12
    • 2017-07-05
    • 2019-01-08
    • 2014-11-23
    相关资源
    最近更新 更多