Error Comparison Between AngularJS Date String and Object

Having an issue retrieving user information by searching firstname in Mongo DB using Mongoose schema. The response includes the firstname and booking date, but the date is returning as undefined with the error message Error: [ngModel:datefmt] Expected `2017-11-06T16:00:00.000Z to be a date. It seems like the problem lies in the fact that type=date expects an object while the JSON is returning a string.

I am relatively new to Angular JS and have attempted various suggested solutions without success. I'm unsure of what I may be missing. Any specific advice based on the provided code would be greatly appreciated.

https://i.sstatic.net/N87Kl.png

HTML

<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>
</form>

Controller

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

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

Service

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) {
            defer.resolve(result.data);
        } 
        else {
            defer.resolve(null);
        }

    }).catch(function (err) {
        console.log(err);
        defer.reject(err);
    });

    return defer.promise;
}     

Server

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

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

    Booking.find({ 
        "firstname" : new RegExp('^'+keyword+'$', "i")
    }, (err, result) => {
        if (err) {
            console.log(err);
        }
        res.status(200).json(result);

        console.log(result); 
        // { _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 №1

Assuming that the variable self.bookings represents an array, it is necessary to iterate over it before converting the string into a date format.

If the date value is undefined, then the current date should be assigned. Otherwise, the string should be converted into a Date object.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error sending an email through the EmailJS backend JavaScript file

I am in the process of creating a route for my backend JavaScript Express server called server.js that will trigger an email to be sent to my Gmail account using EmailJS. When I attempt to use the following code: const SMTPClient = require("emailjs& ...

Adjust the text color of a particular word as you type using the contenteditable property set to "true"

I'm attempting to jazz things up a bit. For instance, I have a div that is set as contenteditable="true". What I want to achieve is changing the color of a specific word I type while writing. In this case, let's say the word "typing" sh ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...

What is the process for converting a Py3k HTTPResponse into json.load?

It was my understanding that json.load() would be able to process objects in the same way as http.client.HTTPResponse, but it seems to be encountering an issue with the read() function being treated as a bytes-like object. (I am working with Python 3.3.) S ...

Altering the contents of a JSON data file using the shell command line

I created a JSON file with the following data: {"ipaddr":"10.1.1.2","hostname":"host2","role":"http","status":"active"}, {"ipaddr":"10.1.1.3","hostname":"host3","role":"sql","status":"active"}, {"ipaddr":"10.1.1.4","hostname":"host4","role":"quad","status ...

Leveraging node.js functions within a gulp task

Seeking guidance on incorporating more-css (https://github.com/army8735/more) into my gulp workflow. After experimenting with various approaches, I am unsure about the syntax needed to include a function of this nature. Can someone provide clarification? ...

various stunning galleries accessible from a single page of thumbnail images

I'm trying to create a unique gallery experience on my website. I have a set of 6 images, each featuring a different house. What I want is for each image, when clicked, to open up a fancybox gallery showcasing 4 more detailed photos of the same house. ...

Which version of Keycloak should I use with Keycloak-js 18.0.0 if my application is running on AngularJS 1.6.0?

When a user tries to log out from the GUI using the provided SIGNOUT button, the logout process fails and the user receives an error message stating 'Invalid parameter: redirect_uri'. Angular-js version: 1.6.0 keyCloak version: 18.0.0 ...

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

Determine the difference between the sizes of two arrays

My current data structure looks like this: [ { name: "A", upvotes: [ "a", "b" ], downvotes: [ "a", "b", "c" ] }, { name: "B", ...

Enhance User Experience with a Customized Progress Bar using Google Apps Script

I created a Google Sheets cell counter in Apps Script and need help setting up the bootstrap progress bar using the "percentage" variable. GS function cellCounter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var ...

Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content. While this solution works perfectly, I encountered a problem where the calculations for ...

Creating a schema for an "array of arrays of objects" in Mongoose.js

I am in the process of creating a schema to represent the following data structure: { ... matrix: [ [{type: "A", count: 6}, {type: "B", count: 4}], [{type: "B", count: 1}, {type: "A", count: 2}, {type: "A", count: 1}], [{type: "C", count: ...

How to Easily Include a New Field in a Mongoose Collection with Node.js

I have a blueprint: var userSchema = new Schema({ name: String, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, admin: Boolean, created_at: Date, updated_at: Date }); Imagine I have constr ...

In a Vue.js application, parameter passing does not function as intended

As someone who is new to JavaScript, I have a question regarding Vuex and creating a simple Todo Manager. I am facing an issue with deleting todos from my list and not getting the desired parameter (the id of the todo) in my actions. Here is the code snip ...

Ways to reduce the size of images within a bootstrap carousel

I'm currently working on creating a carousel that will serve as a background image cover for my website, similar to the revolutionary slider in WordPress but without using a plugin. I am developing it specifically for my static website. The challenge ...

Ways to fetch a JSON object using JavaScript

Currently, I am in the process of creating an HTML5 mobile application and utilizing jQuery to fetch a JSON file from this URL: . Here is the code snippet I used: var url='http://cin.ufpe.br/~rvcam/favours.json'; $.getJSON(url, function(data, s ...

The class `MappedListIterable<dynamic, dynamic>` cannot be assigned to the type `List<Weather>`

I have created three classes to handle JSON parsing from an API call. Here are the classes: class CurrentWeatherInfo { double temperature; double feelsLike; double minTemperature; double maxTemperature; int pressure; int humidity; CurrentWea ...

What methods can I use to prevent an image from moving and trigger a specific action with the press of a key?

I'm currently teaching myself web programming and also working on improving my C++ skills. However, I am facing a challenge with Javascript. My main question is regarding how to create an "if statement" based on the location of an image. I am in the ...

Error encountered while trying to parse the input string "=3" as a number in a Java MongoDB operation: java.util.concurrent.ExecutionException: java.lang.NumberFormatException

filterConditions contains the following conditions: ID>=3, amount<400 String[] fCondition = filterConditions.split(","); if(fCondition[i].contains(">=")){ int indx1= fCondition[i].indexOf("="); int indx2= fConditi ...