简体   繁体   中英

Mongoose - Child Schema References Parent Subdocument

Is it possible to have a Mongoose Schema that resembles the following:

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]
});

Basically a child can only have a category that is contained by its parent. Is what I am trying to do possible? If not what is the cleanest way to do this?

If there is only one field name in categorySchema , maybe you could just put it into parentSchema without population as below,

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

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

When try to insert new child into parent , you could query the parent firstly, then iterate categories to get existing one and add it to children , save the parent as last, sample codes as below

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) {...});
      });  

If there are many fields in categorySchema , maybe define it as individual schema could be one option, in case of there are many categories in Parent to make parent collection too large.

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]
});

The same logic when try to add new children to parent document as above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM