[英]Retrieve value from parent in MongoDB sub-document
I have two schemas 我有两个模式
childrenSchema = new Schema({
name: String
});
parentSchema = new Schema({
type: String,
children: [childrenSchema]
});
Now I want a method in childrenSchema
from which I retrieve the type of the parent. 现在我想在
childrenSchema
一个方法,从中检索父类型。 I guess it is something like 我猜它就像是
childrenSchema.methods.generateName = () => {
// get parent type
};
Do there exist a function like this.parent().type
, ie 是否存在类似
this.parent().type
的函数,即
childrenSchema.methods.generateName = () => {
// get parent type
return this.parent().type;
};
You can do like this : 你可以这样做:
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.