简体   繁体   中英

Mongoose find in referenced document properties

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):

  1. Querying all the results and iterate through them, filtering by code
  2. Saving the nested documents as an array (so not a reference) inside the route model

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM