Angular - Mongoose: Struggling to handle date values

I have been searching for a solution for quite some time now, but unfortunately, nothing has worked for me.

My Angular JS application is running with Mongoose and Express.

I am trying to store date as an object from a simple form. However, after submitting my form, the dates are being stored as strings instead of objects. So I am unable to perform operations like :

tache.start.getDate();

Below is my form :

<form  name="formTache" ng-submit="addTache(tache)">
    <div class="form-group row">
        <div class="col-lg-12">
            <input name="name" class="form-control" placeholder="Name" type="text" ng-model="tache.title"/>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-lg-12">
            <input id="date" name="date" class="form-control" placeholder="Date" ng-model="tache.start" type="date"/>
        </div>
    </div>
    <div class="form-group row">
         <div class="text-right col-lg-12">
            <button type="submit" class="btn btn-default">Add</button>
         </div>
    </div>

Here is my Mongoose Schema :

var restful = require('node-restful');
var mongoose = restful.mongoose;
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var tachesSchema = new mongoose.Schema({
    title : String,
    start: {type: Date, default: new Date()}
});
var tachesModel = mongoose.model('taches', tachesSchema);

module.exports = restful.model('taches', tachesSchema);

Here is my Controller :

angular.module('personaldashboard.tache', [])
  .controller('TachesCtrl', function($scope, Taches, Progress, toaster) {
    $scope.tache = new Taches();
    var refreshTache = function() {
      $scope.taches = Taches.query(); 
      $scope.tache = ''
    }
    refreshTache();

    $scope.addTache = function(tache) {
      Taches.save(tache,function(tache){
        refreshTache();
      });
    };

    $scope.updateTache = function(tache) {
      tache.$update(function(){
        refreshTache();
      });
    };

    $scope.removeTache = function(tache) {
      tache.$delete(function(){
        refreshTache();
      });
    };

    $scope.editTache = function(id) {
      $scope.tache = Taches.get({ id: id });
    };  

    $scope.deselectTache = function() {
      $scope.tache = ''
    }
    $scope.editTache_Projet = function(tache, projetId) {
      tache.projet = projetId;
      tache.$update(function(){
        refreshTache();
      });
    };
    });

This is what I am getting:

{ "_id": "58a99df24975ad0104c692b1", "title": "Test", "start": "2017-02-24T23:00:00.000Z" }

Why am I receiving a string like "2017-02-24T23:00:00.000Z" for my date instead of an object even though my Mongoose schema specifies

start: {type: Date, default: new Date()}
?

Thank you for your assistance.

EDIT

After taking advice from Saurabh Agrawal, I attempted to convert the date within the controller upon submission:

$scope.addTache = function(tache) {
  tache.start = new Date(tache.start);
  tache.end = new Date(tache.end);
  Taches.save(tache,function(tache){
    refreshTache();
  });
};

Unfortunately, this did not bring any change :(

The date still remains as a string

 "2017-02-20T23:00:00.000Z" 

EDIT

I also attempted to add a directive

.directive("formatDate", function(){
  return {
   scope: {ngModel:'='},
    link: function(scope) {
        if (scope.ngModel) {
            scope.ngModel = new Date(scope.ngModel);
        }
    }
  }
})

and called it in my form

<form  name="formTache" ng-submit="addTache(tache)">
    <div class="form-group row">
        <div class="col-lg-12">
            <input name="name" class="form-control" placeholder="Name" type="text" ng-model="tache.title"/>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-lg-12">
            <input id="date" name="date" class="form-control" placeholder="Date" ng-model="tache.start" type="date" formatDate/>
        </div>
    </div>
    <div class="form-group row">
         <div class="text-right col-lg-12">
            <button type="submit" class="btn btn-default">Add</button>
         </div>
    </div>

However, there was no change.

Do you have any other suggestions?

Answer №1

Through my research, I discovered that I had overlooked the true problem at hand.

The dates in question are actually date objects.

When I perform the following code:

$scope.test = new Date([2017,2,15]);

<pre>{{test}}</pre>
<pre>{{test.getDate()}}</pre>

I receive the output:

"2017-02-14T23:00:00.000Z" and 15

This indicates that dates displayed as "2017-02-14T23:00:00.000Z" are considered objects.

However, when attempting the same with a date located within another object schema like this:

 var tachesSchema = new mongoose.Schema({
    title : String,
    start: {type: Date, default: new Date()},
    end: {type: Date, default: new Date()},
    comment : String,
    state : Boolean,
    projet : { type: ObjectId, ref: 'Projets' }
});

No output is generated :(

For instance, when using the code:

<pre>{{tache.start.getDate()}}</pre>

Shows no result.

What did I overlook?

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

Shuffle array elements in JavaScript

I need help with manipulating an array containing nested arrays. Here's an example: const arr = [[red,green],[house,roof,wall]] Is there a method to combine the nested arrays so that the output is formatted like this? red house, red roof, red wall, g ...

Remove any list items that do not possess a particular class

My ul list contains several lis, and I need to remove all li elements that do not have children with the class noremove. This is the original HTML: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>I ...

The requested command is not being recognized

Just starting out with these commands as I dive into learning Angular.js through a book. npm install –g grunt-cli npm install –g bower npm install –g generator-angular After successfully running all the commands, I attempted to create a folder in C ...

In a Django template, implement a checkbox feature in the list view to select multiple objects. Retrieve all selected checkbox objects for each pagination and display them in

In my HTML template, I have a list view with checkboxes and pagination. My goal is to retrieve all the checked box objects from each page's pagination and send them to the server (specifically the view part of Django). For example, if I check 4 object ...

Seeking assistance with my basic JavaScript/jQuery programming

I have a navigation menu link with an ID #navigation li a and a description with a class .menu-description. I would like to update the class from .menu-description to .menu-descriptionnew whenever a user hovers over #navigation li a. Here is my current jQ ...

Make sure to not update until all the necessary checks have been completed successfully

My goal is to update an array of objects only after all the necessary checks have passed. I have one array of objects representing all the articles and another array of objects representing the available stock. I want to make sure that all the articles ar ...

Adding a timestamp in JSON format for insertion into a MongoDB time series data collection

When it comes to working with the MongoDB API, /action/insertOne is typically smooth sailing for standard data. However, we've hit a roadblock when trying to apply it to a time series database. We keep encountering the error message: ‘t’ must be ...

Guide on how to navigate to the bottom of a div element using Selenium Webdriver

My current project involves a unique challenge where there is a specific div element on the webpage that acts as a popup dialog when a link is clicked (similar to Facebook reaction dialog boxes). To automate tests for this scenario, I am using Selenium We ...

Tips on saving all objects, even those that are repeated, in a JavaScript array

My goal is to store and display all objects, even if they are repeated, but the current setup only allows for storing unique values. The positive aspect is that it calculates the total by summing up all values, including duplicates. The Negative aspect is ...

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Automatically selecting a row within Material-UI's data grid using React code

Currently, I am in the process of developing a React web application and utilizing DataGrid from Material-UI by Google. The grid displays based on the user's selection from a select list (e.g., if the select list consists of fruits and the user choose ...

Is there a built-in method in MongoDB to retrieve results as objects rather than arrays?

I have searched through some old similar queries on Stack Overflow but haven't had any luck finding the correct solution. In my MongoDB query, I am using async/await to retrieve data from the database. The code snippet looks like this: (async () => ...

Determine the frequency of a specific letter in JavaScript by utilizing the indexOf method

Hey there! I'm currently working on a code to count the occurrences of a specific letter in a string using indexOf(). However, it seems like something may be off with my implementation. Can anyone point me in the right direction? Thanks! var string = ...

Introducing HTML elements into pre-existing web pages

My interest lies in the idea of injecting HTML into existing web pages for enhanced functionality. Specifically, I am exploring the concept of creating a more efficient bookmarking system. As someone new to web development, I am unsure of how to achieve th ...

Using Node.js to update multiple documents in MongoDB with an index applied

Is there a way to incorporate the current document's number or index into the updateMany method in MongoDB using Node.JS? For instance: db.collection("users").updateMany({}, { $set: {"uname": "user_" + $index}}); Where $index represents the specifi ...

Expanding Gridview Width within a Container in ASP.Net: A Step-by-Step Guide

https://i.stack.imgur.com/ZaJE7.jpg After viewing the image above, I am facing a challenge with stretching and fixing a gridview to contain the entire div where it is placed. The issue arises when the gridview adjusts automatically based on the content&ap ...

Determine all the names of imported files in a source file using regular expressions in JavaScript

Hello, I'm new to working with regex and JavaScript. I'm attempting to use regex to create an array of all imported files in a source file. In the source file, there is an '@' sign before an import statement. For example, if the file lo ...

Enhancing MongoDB Performance by Modifying Array Elements within Arrays

What is the most efficient method for updating an element within an array in MongoDB? Take, for example, this dataset: { "_id" : ObjectId("6201396b866ffbf1b84fb8f9"), "title" : "ironman", &quo ...

How can I display a customized component on a table based on the data object's value?

I am working on a custom Table component that I want to render based on an array of objects. The challenge is that I need the Table component to have two props: one for the data object and another for an array of objects, each containing a title and a func ...

No matter what I try, the design of my dialog box remains stubbornly unchanged

I am attempting to increase the width of my dialog box while also adding horizontal middle borders. It seems that my bootstrap for the site does not include these elements. How can I rectify this issue? Here is my code: $(document).ready(function() { ...