ManyArray.length is undefined


#1

Hi experts,

I’m creating a model which has a one to many relationship. e.g.

Node = DS.Model.extend({ children: DS.hasMany(‘Node’) };

When I try to access Node.children.length, I get undefined. I can work around this issue by using Node.children.toArray().length. My question is at the documentation itself. When I looked at the API document, It doesn’t say that length just returns undefined. Is it the expected behavior or should it be documented? It seems length behaves not straightforward.


#2

have you tried Em.get(Node, 'children.length')?


#3

@kceiw @tarasm I’ve encountered this issue a few times, and neither toArray().length nor Em.get(Node, 'children.length') has appeared to be a solution with any reliability, especially if you want to get the length without needing to actually load the content from the server.

The attribute I use when I need the length without loading: [record]._data.[attribute].length

If I had to hazard a well formed guess, the [record].[attribute].length attribute either never gets correctly set from where I’m retrieving it, or it isn’t supposed to be set until there are actually records loaded and present, in which case it is the length of the loaded records array, not the length of the references array.


#4

@tarasm No. I didn’t know that I could try that. But as @jthoburn pointed out. It’s not reliable.

I agree with @jthoburn that getting the length without needing to load the content is important. Sometimes the whole content is not needed right now and the loading can be deferred.

[record]._data seems to be implementation. It’s a workaround but I’m afraid that it won’t work when the implementation changes.

I hope there is a well documented, reliable way to get the length.


#5

I agree this should be a thing that you don’t have to rely on _data for, and lazy record loading is the entire reason getting the length before loading matters. I’d be curious what @wycats or @stefan think, perhaps there’s something we’ve overlooked?


#6

Actually it looks like @wycats has already weighed in: https://github.com/emberjs/data/issues/586

Worth perusing (there’s a related issue with some discussion of it as well near the bottom). I haven’t found the discourse (discuss?) thread that he mentions though.


#7

Those issues are complaining loading the data unnecessarily (it seems not solved yet). If the data is loaded, then the question is why length is not set.