Reputation: 2533
I'm new to Mongo and would love some help!
I have a Parent References tree structure which looks like this:
Object {
_id: <some id>
parent: <an _id or null if topmost>
allowed : [userIds]
}
I'd like a query that returns all objects whose topmost parent has this user id in the allowed list. The topmost parent is the one whose parent is null, and the topmost parent should also be returned as part of the query.
Typically, a tree will have 1-10 levels but could be more. Should I be worried about performance?
Upvotes: 1
Views: 2206
Reputation: 2533
I've figured it out, for whomever needs this. You have to do two queries basically:
// 1 - GET THE ANCESTORS
var allowedAncestorIds = [];
Objects.find({
parent: null,
allowed: this.userId
}).forEach(function (ancestor) {
// 2 - STORE THEIR IDs
allowedAncestorIds.push(ancestor._id);
});
return Objects.find({
$or: [
// 3 - USE THE ALLOWED ANCESTOR IDs IN THE QUERY TO GET ALL THE OBJECTS
{parent: {$in: allowedAncestorIds}},
{allowed: this.userId}
]
});
Upvotes: 1