Knexjs returning mysql timestamp, datetime columns as Javascript Date object

大兔子大兔子 提交于 2019-12-05 16:56:49

Change your connection object with this:

var connection = require('knex')({
        client: 'mysql',
        connection: {
            host: db.host,
            user: db.user,
            password: db.password,
            database: db.database,
            timezone: 'UTC',
            dateStrings: true
        }
   });

This is how mysql driver converts types read from database to javascript (https://github.com/mysqljs/mysql#type-casting)

You can override default conversion by adding typeCast connection option:

var moment = require('moment');
var connection = require('knex')({
        client: 'mysql',
        connection: {
            host: db.host,
            user: db.user,
            password: db.password,
            database: db.database,
            timezone: 'UTC',
            typeCast: function (field, next) {
              if (field.type == 'DATETIME') {
                return moment(field.string()).format('YYYY-MM-DD HH:mm:ss');
              }
              return next();
            }
        }
   });

I'm not sure if you need to add custom parsing for DATETIME or TIMESTAMP type though.

In my case, the connection was a string so I had to find the date OID and use pg.types.setTypeParser(DATE_OID, d => moment(d));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!