【问题标题】:How to access instance of sub document in mongoose from parent instance?如何从父实例访问猫鼬中子文档的实例?
【发布时间】:2016-06-02 00:21:54
【问题描述】:
   var mongoose = require('mongoose');
   var Schema = mongoose.Schema;

   var ChildSchema = new Schema({
       name: String
   });

   ChildSchema.methods.getName = function () {
       return this.name;
   }

   var ParentSchema = new Schema({
       children: {
            type: [ChildSchema]
            default: []
       }
   });

   ParentSchema.methods.getChildName = function () {
       // How to facilitate ability to access instance of ChildSchema to call child.getName
   }
   var Parent = mongoose.model('Parent', ParentSchema);

在上面的代码中,我希望在ParentSchema 中访问ChildSchemagetName 方法。在mongoose中怎么做?

非常感谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    请尝试使用subdocument index作为下面的参数。

    ParentSchema.methods.getChildName = function (idx) {
       return this.children[idx].getName();
    }
    
    var p = new Parent({
        children: [{ name: 'Matt' }, { name: 'Sarah' }] 
    });
    
    console.log(p.getChildName(1));  // Sarah
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      相关资源
      最近更新 更多