Mongoose - 子模式引用父子文档

fqh*_*qhv 5 javascript mongoose mongodb node.js

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

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]
});
Run Code Online (Sandbox Code Playgroud)

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

zan*_*ngw 4

name如果中只有一个字段categorySchema,也许你可以将其放入parentSchemawithout中population,如下所示,

var childSchema = new Schema({
   name : String,
   category : {
      name: String
   }
});

var parentSchema = new Schema({
    categories : [{name: String}],
    children : [childSchema]
});
Run Code Online (Sandbox Code Playgroud)

当尝试插入 newchild到时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) {...});
      });  
Run Code Online (Sandbox Code Playgroud)

如果 中有很多字段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]
});
Run Code Online (Sandbox Code Playgroud)

children尝试向文档添加新内容时的逻辑parent与上面相同。