miintea miintea - 3 months ago 45
JSON Question

AngularJS Date string vs object error

I'm trying to retrieve a set of user information (by searching firstname) and it returns firstname and booking date (from mongoDB, mongoose schema uses date: Date). Firstname is type=text and booking date is type=date. It returns date as undefined and error message is Error: [ngModel:datefmt] Expected `2017-11-06T16:00:00.000Z to be a date. I read other questions/answers that it's because type=date expects an object but the JSON is returning a string.

I'm really new to Angular JS and I've tried the suggested methods but no result. I don't know what is missing. Appreciate any specific pointers based on my code

enter image description here


<form name="updateBookingsForm" ng-repeat="booking in ctrl.bookings" novalidate>
<input name="firstname" type="text" ng-model="booking.firstname" class="form-control" required>
<input name="date" type="date" ng-model="booking.date" class="form-control" required>


self.searchAllBookings = function () {
paAppAPI.searchAllBookings(self.term).then(function (result) {
console.log(result); //returns array and date undefined
self.bookings = result;

}).catch(function (err) {
if (err.status == 404) {
self.message = "No bookings found";
self.showMessage = true;


self.searchAllBookings = function (term) {
var defer = $q.defer();

$http.get("/api/booking?keyword=" + term).then(function (result) {
console.log(result); //returns array but date undefined
if (result.status == 200) {
else {

}).catch(function (err) {

return defer.promise;


app.get("/api/booking?", function (req, res) {

console.log("Search booking > " + req.query.keyword);
var keyword = req.query.keyword;

"firstname" : new RegExp('^'+keyword+'$', "i")
}, (err, result) => {
if (err) {

// { _id: 5a1a4e1238dfaa65e5fa59a2,
// firstname: 'Emily',
// date: 2017-11-20T16:00:00.000Z,
// __v: 0 },

console.log(result[0].date); //2017-11-06T16:00:00.000Z


Answer Source

I assume self.bookings is an array. If so need to loop it over before converting the string to the date.

And then if the date is undefined assign the current date. Otherwise converts the string to Date.

.then(function (result) {
    console.log(result); //returns array but date is undefined
    self.bookings = result;
    for(var i=0; i< self.bookings.length; i++){
       self.bookings[i].date = new Date(self.bookings[i].date) : Date.now())

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download