![](/img/trans.png)
[英]NodeJS with MongoDB - Get Nested Collection matching one of an array objects
[英]How to get the connected objects within a collection in an array in Mongoose MongoDb NodeJS
我是NodeJS的新手,并且正在使用NodeJS Framework HapiJs。 我有一个模型“元素”的父子模式,其中父项和子项属于同一集合。 该架构类似于以下内容:
var mschema = new Schema({
autoIncrementId: { type: Number,unique: true,index:true,sparse:true},
elementName: {
type: String,
required: true
},
elementCanvasId: {
type: String,
required: true
},
parentId: {
type: Schema.Types.ObjectId,
required: false,
ref: "Elements",
},
parentCanvasId: {
type: String,
required: false
},
});
var modules = Mongoose.model('Elements', mschema);
这里elementCanvasId
是在客户端生成的。 parentCanvasId
是对父元素的elementCanvasId
的引用。 同样,每个元素都不必具有父元素。 现在,基于元素的elementCanvasId
,我想在一维数组中获取该元素的层次结构下的所有元素(即,其所有子元素,然后是子元素的子元素,然后是子元素的子元素,依此类推。) 我不能为此目的使用Schema.Types.ObjectId
,因为我只需要使用仅在客户端生成的elementCanvasId
。 因此,有人可以帮我完成它。 任何帮助都将不胜感激。 提前致谢。
我认为您正在寻找的是$graphLookup
,但是只能从3.4+版本开始使用,它变得非常复杂
有关完整详细信息,请参见https://docs.mongodb.com/v3.4/reference/operator/aggregation/graphLookup/
Elements.aggregate( [
{
$graphLookup: {
from: "elements",
startWith: "$parentCanvasId",
connectFromField: "parentCanvasId",
connectToField: "elementCanvasId",
as: "elementHierarchy"
}
}
] )
您需要使用$ graphLookup 。 由于$ graphLookup对集合执行递归搜索。
Elements.aggregate([{ $graphLookup : {
from : 'elements', // MongoDB collection name not mongoose schema name
startWith : '$parentCanvasId', //it is expression which can include can include field paths and system variables, literals, expression objects etc.
connectFromField : 'elementCanvasId',
as : 'children'
} }])
如果您只想获取一个元素的元素层次结构,则需要在聚合管道中使用$ match
Elements.aggregate([{ $match : { autoIncrementId : '1' } }, { $graphLookup : {
from : 'elements', // MongoDB collection name not mongoose schema name
startWith : '$parentCanvasId',
connectFromField : 'elementCanvasId',
as : 'children'
} }])
注意: autoIncrementId:1是获取单个元素的结果的条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.