I have a schema like this...
var TerritorySchema = new Schema({
user: Schema.Types.ObjectId,
streets: [streets_schema]
)};
var StreetsSchema = new Schema({
name: String,
odd: [block_schema],
even: [block_schema],
tags: [String]
)};
In need to be able to find a territory by a users id. However, I then need to find a street by name within the streets inside the returned document. This is how I'm doing it...
TerritoryModel.findOne({user: userId})
.then(territory => {
// now i have my territory parent object
// and must find street by name
var streetINeedToFind = null;
for(i = 0; i < territory.streets.length; i++){
var street = territory.streets[i];
if(street.name === streetNameToFind){
streetINeedToFind = street;
break;
}
}
})
// catch blah blah blah ... you know
I am new to the NoSQL scene and I just feel like I should be able to query for the street I need, and have the database do all the searching for me.
The territory schema is actually a lot larger than what I defined above, and I am going to need to query for more deeply nested subdocuments (e.g house within a street etc). Is there a way to query within a document or some other easier way to uncover subdocuments, rather than looping through them?
I read up on aggregation but I'm not sure if that's what I need? I may be wrong, maybe what I'm doing is best practice, could someone please show me way?