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 ing 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
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 ing 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
Share Improve this question asked Sep 24, 2017 at 12:42 George EdwardsGeorge Edwards 9,22921 gold badges85 silver badges171 bronze badges2 Answers
Reset to default 6You 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()
},
To plement 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.