Node.js 如何从父实例访问mongoose中的子文档实例?

Node.js 如何从父实例访问mongoose中的子文档实例?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,在上面的代码中,我希望访问ParentSchema中ChildSchema的getName方法。如何在猫鼬身上做到这一点 非常感谢。请尝试使用子文档索引作为参数,如下所示 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ChildSchema = new Schema({ name: String }); ChildSchema.methods.getNam

在上面的代码中,我希望访问
ParentSchema
ChildSchema
getName
方法。如何在猫鼬身上做到这一点


非常感谢。

请尝试使用
子文档索引作为参数,如下所示

   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.methods.getChildName = function (idx) {
   return this.children[idx].getName();
}

var p = new Parent({
    children: [{ name: 'Matt' }, { name: 'Sarah' }] 
});

console.log(p.getChildName(1));  // Sarah