简体   繁体   English

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

[英]Retrieve value from parent in MongoDB sub-document

I have two schemas 我有两个模式

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

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

Now I want a method in childrenSchema from which I retrieve the type of the parent. 现在我想在childrenSchema一个方法,从中检索父类型。 I guess it is something like 我猜它就像是

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

Do there exist a function like this.parent().type , ie 是否存在类似this.parent().type的函数,即

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

You can do like this : 你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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