I'm going nuts on a query to find a match based on referenced document properties. I've defined my schema like this:
mongoose.model('Route', new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}));
mongoose.model('Match', new mongoose.Schema({
route: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Route'
}
}));
So when I'm searching for a route from a specific user in the Match model, I'd do something like (also tried without the '_id' property):
match.find({'route.user._id': '53a821577a24cbb86cd290d0'}, function(err, docs){});
But unfortunately it doesn't give me any results. I've also tried to populate the model:
match.find({'route.user._id': '53a821577a24cbb86cd290d0'}).populate('route').exec(function(err, docs){});
But this doesn't make a difference. The solutions I'm aware of (but don't think they're the neatest):
Anyone suggestions? Many thanks in advance!
Related questions (but not a working solution offered):
I'm going nuts on a query to find a match based on nested document properties
You don't have nested documents. You have references, which are just IDs that point to documents that reside in other collections. This is your basic disconnect. If you really had nested documents, your query would match.
You are encountering the "mongodb does not do joins" situation. Each MongoDB query can search the documents within one and only one collection. Your "match" model points to a route, and the route points to a user, but the match does not directly know about the user, so your schema does not support the query you want to do. You can search the "routes" collection first and use the result of that query to find the corresponding "match" document, or you can de-normalize your schema and store both the routeId and userId directly on the match document, in which case you could then use a single query.
Based on your question title, it seems like you want nested documents but you are defining them in mongoose as references instead of real nested schemas. Use full nested schemas and fix your data, then your queries should start matching.