Using 'at' syntax


Say I want to do:

var x = User.fetch()

in a safe way using the ‘at’ function.

Would I do

var x = User.fetch().at(‘objs[0]’)

or maybe

var x = User.fetch().at(‘objs’).at(0)

or maybe something else?



The former.

If fetch returns no results, the objs field will be undefined so


will return undefined, producing an error when you try to access .at.

If you use the former syntax, at will return undefined if either the objs field is null/undefined or an empty array. This doesn’t make as much difference in this case, but it would if you then continue to pluck a field out of the first fetched object:

var name = User.fetch().at('objs[0].name')

Here at will return undefined without triggering a JavaScript error if:

  • objs is undefined/null
  • objs is an empty array
  • objs[0] is undefined/null

Compare this to:

  var result = User.fetch();
  var name = (result.objs && result.objs.length > 0) ? result.objs[0].name : undefined;