js-data-rethinkdb icon indicating copy to clipboard operation
js-data-rethinkdb copied to clipboard

`orderBy` with dates

Open mikew opened this issue 8 years ago • 1 comments

Whenever I use orderBy with a date the results are never consistent.

With this code:

export const SurveyError = defineMapper({
  name: 'SurveyError',
})

function populate () {
  const fullDay = 24 * 60 * 60 * 1000
  const now = new Date()

  return Promise.all([
    SurveyError.create({ happenedAt: new Date(now - fullDay * 0) }),
    SurveyError.create({ happenedAt: new Date(now - fullDay * 1) }),
    SurveyError.create({ happenedAt: new Date(now - fullDay * 2) }),
    SurveyError.create({ happenedAt: new Date(now - fullDay * 3) }),
  ])
}

function logDates () {
  return SurveyError
    .findAll({ orderBy: [ [ 'happenedAt', 'asc' ] ] })
    .then(items => {
      console.log(items.map(x => x.happenedAt))
    })
}

populate()
  .then(logDates)
  .catch(console.error)

You can run it multiple times and get different results:

// Run 1
[ 2016-12-04T20:56:12.288Z,
  2016-12-05T20:56:12.288Z,
  2016-12-06T20:56:12.288Z,
  2016-12-03T20:56:12.288Z ]

// Run 2
[ 2016-12-04T20:58:21.900Z,
  2016-12-05T20:58:21.900Z,
  2016-12-06T20:58:21.900Z,
  2016-12-03T20:58:21.900Z ]

// Run 3
[ 2016-12-06T20:58:37.565Z,
  2016-12-05T20:58:37.565Z,
  2016-12-03T20:58:37.565Z,
  2016-12-04T20:58:37.565Z ]

Should the dates be stored as an integer?

mikew avatar Dec 06 '16 21:12 mikew

Storing as an integer could work, but I think you'd want them stored as Rethink's native Time type. How does it work for you if you construct your dates with r#time() instead of new Date()?

jmdobry avatar Dec 12 '16 05:12 jmdobry