Dates with AngularJS Resources, Mongoose and Express

As you may know, the past few weeks have been spent with me working with Node and Express to re do this blog site of mine. And as you may know, part of writing a custom CMS (Content Management System) is writing an effective back end to create your content to be displayed on the site. Just as something different, I have decided that I use AngularJS to interact with my Express RESTful API.

JavaScript

Using $resource to handle the bulk of the data exchange, the Angular back end has come together really quickly. I am very happy with the progress thus far.

That being said, I hit a stone wall while working with the publish date time input field. I had checked that the date being sent by express was indeed a proper javascript timestamp, and that the data angular was receiving was the same string being sent out. So it a was complete mystery to me as to why AngularJS was telling me that my publish date was not a valid date format.

First thing I tried was to force a different output from Mongoose in the hopes that Angular would be able to parse the date if passed in a different format. This did not work.

Next I tried using one of Angular's filters to handle the data. But this produced the same error, that Angular could not parse the data time.

So after this, I evaluated the data coming back from express a little more closely. It turns out that Angular is not converting the date string into a date object to used. I had made the incorrect assumption that this would be handled automatically.

So, what I needed was a way to manually convert the data into JavaScript Date objects. Thankfully, using the $resource get method, you can pass an anonymous function as a second parameter to modify the data after the fact.

So what this allows for me to do, is to pass the date field into a new Date Object which Angular is then able to work with. Problem Solved!