Objection.js: Possible optimization with first() method

Created on 21 Feb 2017  路  4Comments  路  Source: Vincit/objection.js

Looking through the source code I noticed that the first query method pulls down the entire dataset and then returns the first element in the array. A possible optimization to this would be to automatically append limit(1) if not present in order to limit the returned dataset to just one record. Thoughts?

wontfix

Most helpful comment

Also curious about this one, when using first(), limit is not added to the query, so basically what you have to do is:

const user = await User.query().where('id', id).limit(1).first()

Looks a bit weird and is not mentioned in the docs. (or maybe I didn't find)

Maybe something has changed since issue was created so limit can be added by default?

All 4 comments

That's exactly what knex.QueryBuilder#first does though. Does objection.QueryBuilder#first have a different use case?

The first method was meant to be more like a shortcut to .then(_.first) but maybe we could add the limit(1) there without breaking too many things. We should try to be compatible with knex as much as possible.

This would break join based eager queries as well as any usage with update and insert* methods. Maybe we shouldn't do this. I'll add a mention to the documentation that this doesn't modify the database query. limit(1) needs to be used in addition to get the performance benefits.

Also curious about this one, when using first(), limit is not added to the query, so basically what you have to do is:

const user = await User.query().where('id', id).limit(1).first()

Looks a bit weird and is not mentioned in the docs. (or maybe I didn't find)

Maybe something has changed since issue was created so limit can be added by default?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

haywirez picture haywirez  路  3Comments

Gustav0ar picture Gustav0ar  路  4Comments

purepear picture purepear  路  3Comments

chen7david picture chen7david  路  3Comments

rickmed picture rickmed  路  4Comments