我有两个架构
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;
};
答案 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
});