3

I have the following sequelize query:

let prms = periods.map((period, index, arr) => {
    if (arr[index + 1]) {
        return sequelize.models.Result.aggregate('value', 'avg', {
            where: {
                createdAt: {
                    $lt: arr[index + 1],
                    $gt: period
                },
                type: hook.params.headers.type,
                entityId: hook.params.headers.entity
            }
        }).catch(err => console.log('err'));
    }
})

Now, the createdAt property on the where object is causing me this problem:

error: Error: Invalid value 1506211200000 at Object.escape (C:\Users\George\Source\Repos\myProj\node_modules\sequelize\lib\sql-string.js:50:11) at Object.escape (C:\Users\George\Source\Repos\myProj\node_modules\sequelize\lib\dialects\abstract\query-generator.js:917:22)

Now I don't have any idea where the 1506211200000 number is coming from, both arr[index + 1] and period are moment.js objects, and I can verify this by doing console.log(arr[index + 1].isValid(), period.isValid()); which prints true true. If remove the createdAt restriction, there is no issue.

Any idea what is going on here?

NB: I am using Postgres

George Edwards
  • 8,979
  • 20
  • 78
  • 161

2 Answers2

6

You need to convert moment object to Date object using moment#toDate method, to use it in sequelize query:

...
createdAt: {
  $lt: arr[index + 1].toDate(),
  $gt: period.toDate()
},
alexmac
  • 19,087
  • 7
  • 58
  • 69
0

To complement on the accepted answer: If you need it to be timezone aware, you will probably need to use the format method from the moment object. Like so:

...
where: {
  createdAt: {
    Op.lt: arr[index + 1].format(),
    Op.gt: period.format()
  }
...
}

Using the toDate method, it will use the local timezone, so you might get seemingly byzantine errors when deploying code to production, as the machine where you're deploying might have a different timezone from your local machine.

You can read further regarding this topic here.