How to return deep nested objects in Ottoman.js that are more than 1 level deep?

Given that I have say three model objects: Parent, Child and NestedChild, where the Parent model contains an array of referenced Child models which in turn also contains an array of referenced NestedChild models.

For example

const parent = ottoman.model("Parent", {
    child: [{ref: "Child"}],
    foo: "string"
 });

const child= ottoman.model("Child", {
    nestedChild: [{ref: "NestedChild"}],
    bar: "string"
});

const nestedChild= ottoman.model("NestedChild", {
    baz: "string"
});

I understand how to get the child reference such as:

getNestedObjects.find({}, {load: 'child'}, function(err, results) {
  // results will be populated here...
})

which returns

{
  "parent": [
    {
      "child": [
        {
          "nestedChild": [
            null,
            null,
            null
          ],
          "foo": "Foo"
        }
      ],
      "bar": "Bar"
    }
  ]
}

As you can see the NestedChild objects return as null.
My question is how do I load the NestedChild and any other children below that however deep?

Hey @f.reynolds,

There are a few ways you can do this. One option is to manually load the nestedChild objects that you are interested in (just call .load() on them), keeping in mind that in spite of them returning null in your JSON output, they are in fact real objects, but unloaded with no data. Another option is to load every nestedChild in every child object. You can do this by specifying something like {load: ['child', 'child[*].nestedChild']}.

Cheers, Brett

Thanks for the quick response. I did some digging in the code and looked at the jsonpath spec. I did manage to get it working like you said but took me a while to figure out you had to declare child first then child[].nestedChild and the same for any children of nestedChild. I first thought that child[].nestedChild was enough.

Thanks again and for the .load() tip.

Cheers, Fabrice

Hey Fabrice!

I’m glad you got it working. Ottoman v2 is on the horizon and I added a note to make sure we document how the behaviour here works better than we had in previous iterations. Let us know if you run into any more issues or have any more questions!

Cheers, Brett