3

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?

1 Answers1

0

If you've already queried for the full document, then you can directly use standard JS array methods like find:

var streetINeedToFind = territory.streets.find(s => s.name === streetNameToFind);

However, if you only need specific parts of the document, then you can use the query projection techniques from this other question to do that.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • I opted for using standard JS methods, it works out better for me in the end because I am going to need access to the parent object to call the "save" method when I modify the subdocument. – Julian Hernandez Dec 13 '18 at 03:10