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

标签 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;
};

最佳答案

你可以这样做:

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

关于javascript - 从 MongoDB 子文档中的父级检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314701/

相关文章:

c# - 如何使用 c# 2.0 驱动程序将数据插入到 mongodb 集合中?

javascript - 我可以绕过可选参数并仍然在 Javascript 中设置剩余参数吗?

javascript - 检测每个用户是否单击了所有按钮

javascript - 使用 ng-file-upload 和 mongo gridfs 上传文件

Javascript 调用在文本框更改时具有旧值

javascript - 找不到模块的声明文件

Node.js 检查是否存在多个具有非特定扩展名的文件

javascript - 获取原始参数输入 - Dialogflow Fulfillment

C# + MongoDB - 不使用 MongoDB 数据类型/属性的 ObjectId

javascript - 如何使用Meteor和MongoDB从数组中的对象返回子文档