从MongoDB子文档中的父级检索值

时间:2016-09-04 07:49:19

标签: javascript node.js mongodb mongoose subdocument

我有两个架构

childrenSchema = new Schema({
  name: String
});

parentSchema = new Schema({
  type: String,
  children: [childrenSchema]
});

现在我需要childrenSchema中的一个方法,我从中检索父类型。我想这就像是

childrenSchema.methods.generateName = () => {
  // get parent type
};

是否存在类似this.parent().type的功能,即

childrenSchema.methods.generateName = () => {
  // get parent type
  return this.parent().type;
};

1 个答案:

答案 0 :(得分:0)

你可以这样做:

 childrenSchema = new Schema({
      name: String
    });

    childrenSchema.methods.generateName = () => {
      // get parent type
      return this.ownerDocument().type;
    };

    parentSchema = new Schema({
      type: String,
      children: [childrenSchema]
    });

    var childModel = mongoose.model('Children', childrenSchema);
    var parentModel = mongoose.model('Parent', parentSchema);

    var parent = new parentModel({type: 'Scifi'});
    parent.children.push(new childModel({name: 'Star wars'}));

    parent.save(function(err, doc){
      console.log(doc.children[0].generateName()); // Scifi
    });