我有两个架构
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/