dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

not able to save javascript Date() Object in date field in mysql #749

Closed apmeena closed 7 years ago

apmeena commented 7 years ago

I have some date filed in MySQL database, in ORM model i am defining the date field like this:

expiryDate : { type: 'date' },

and in database table the field type is date, i have the value of date field like this

Fri Dec 30 2016 00:00:00 GMT+0530 (India Standard Time)

if i am sending this date value to ORM for create or update operation it is generating this error:

{ [Error: ER_TRUNCATED_WRONG_VALUE: Incorrect date value: 'Fri Dec 30 2016 00:00:00 GMT+0530 (India Standard Time)' for column 'latestShipmentDate' at row 1] code: 'ER_TRUNCATED_WRONG_VALUE', errno: 1292, sqlState: '22007', index: 0 }

To avoid this error i am converting the date in yyyy-mm-dd format before sending to ORM, but ORM should convert it because we are saying expiryDate : { type: 'date' }, is there any setting or trick to avoid this date conversion before sending to the ORM?

noopuraspire commented 7 years ago

I'm facing the same issue. Any update on it??

apmeena commented 7 years ago

@noopuraspire I have solved the issue using custom types, It is working fine for me. You can look into my code:

db.defineType('date', {

      datastoreType: function (prop) {

        return 'TEXT'

      },

      // valueToProperty
      valueToProperty: function (value, prop) {

        if (!isNaN(Date.parse(value))) {
          var d = new Date(value);
          if (typeof d.getMonth === 'function' || d instanceof Date || Object.prototype.toString.call(d) === '[object Date]'){
            return d;
          } else {
            return null;
          }
        } else {

          return null;

        }

      },

      // propertyToValue
      propertyToValue: function (value, prop) {

        if (!isNaN(Date.parse(value))) {
          var d = new Date(value);
          if (typeof d.getMonth === 'function' || d instanceof Date || Object.prototype.toString.call(d) === '[object Date]'){
            return d;
          } else {
            return null;
          }
        } else {

          return null;

        }

      }

    });

You need to place this code at App->Models->index.js.

I hope it will be helpful. Thanks.