Knexjs returning mysql timestamp, datetime columns as Javascript Date object

会有一股神秘感。 提交于 2020-01-02 05:44:35

问题


i am using knexjs i insert data in the format YYYY-MM-DD HH:mm:ss e.g 2017-07-14 15:00:00 and after saving when the data is fetched the datetime column values are returned as javasript Date object. i want to return those object in the format YYYY-MM-DD HH:mm:ss but it returning in the format YYYY-MM-DDTHH:mm:ss.000Z e.g 2017-06-23T06:44:44.000Z. i am returning them by iterating and converting them manually. i was wondering if there is another way to do it like in mysql driver or knexjs configuration. currently my knexjs configuration is this.

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

回答1:


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
        }
   });



回答2:


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.




回答3:


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));



来源:https://stackoverflow.com/questions/45103788/knexjs-returning-mysql-timestamp-datetime-columns-as-javascript-date-object

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