1

I'm working with SailsJS and MongoDB and I have an API that has two models and I want to store Date and Time separately but as in the official documentation said it doesn't have a typeof Time attribute, just Date and DateTime. So, I'm using DateTime to store Time values.

I send the values in the request to be stored in the database, I have no problem to store dates, I just send a value like:

2015-12-16

and that's it, it is stored in the table with no problem, but when I want to store a Time value like:

19:23:12

it doesn't works. The error is:

{
  "error": "E_VALIDATION",
  "status": 400,
  "summary": "1 attribute is invalid",
  "model": "ReTime",
  "invalidAttributes": {
    "value": [
      {
        "rule": "datetime",
        "message": "`undefined` should be a datetime (instead of \"19:23:12\", which is a string)"
      }
    ]
  }
}

So, any idea how to send the time value to be stored in a DateTime attribute?

I also have tried to send it in different formats like:

  • 0000-00-00T19:23:12.000Z
  • 0000-00-00T19:23:12
  • T19:23:12.000Z
  • 19:23:12.000Z
  • 19:23:12

But any of them works fine.

Also I was thinking to store both values (Date and Time) in plain text, I mean typeof String attributes. But I need to make some queries and I don't know if it will affect the performance with the waterline ORM.

Please any kind of help will come in handy. Thanks a lot!

alexventuraio
  • 8,126
  • 2
  • 30
  • 35

1 Answers1

0

You have two options here. The best would be to simply store the date and time as a datetime and parse them into separate values when you need to use them. MongoDB will store this in BSON format and this will be the most efficient method.

Otherwise, you could use string and create a custom validation rule as described in the Sails documentation.

Community
  • 1
  • 1
this-sam
  • 182
  • 1
  • 14
  • Thank you so much! But how can I parse the data as you mention in order to use it and show to the user? I'm new in JavaScript – alexventuraio Dec 17 '15 at 01:59
  • I'm not exactly sure how it will be returned from the database. Either it will come back as a JavaScript `Date` itself, or you will need to instantiate a new `Date` with the value you get. Check out the [Date reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) here. The top shows you how to instantiate (`var datetime = new Date(value_from_db);`). If you look at the prototype methods, you can see how to get various pieces of the date or time from the object. – this-sam Dec 17 '15 at 19:51