What is the best way to utilize my data with Charts.js for my specific situation?

I am utilizing Charts.js in my Angular project (not AngularJS) and I am trying to create a graphic representation with data from my database that shows the distribution between men and women. However, I am struggling to figure out how to loop through the data to count the number of men and women:

Firstly, for the Chart, here is my HTML code :

<canvas id="myChart" width="700" height="400"></canvas>

Typescript code :

ngAfterViewInit() {
    this.canvas = document.getElementById('myChart');
    this.ctx = this.canvas.getContext('2d');
    let myChart = new Chart(this.ctx, {
      type: 'pie',
      data: {
          labels: ["Female", "Male"],
          datasets: [{
              label: '# of Votes',
              data: [2, 2],
              backgroundColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)'
              ],
              borderWidth: 1
          }]
      },
      options: {
        responsive: false,
        display:true
      }
    });
  }

and the code to fetch my data :

Javascript :

app.get("/api/getUser",function(req,res){
    model.find({},function(err,data){
              if(err){
                  res.send(err);
              }
              else{
                  res.send(data);
                  }
          });
  })

Typescript :

GetUser(){
    return this.http.get('http://localhost:8080/api/getUser/')
            .map((response: Response) => response.json())
  }

and another piece of Typescript :

 ngOnInit() {
    this.newService.GetUser().subscribe(data =>  this.Repdata = data)
  }

Finally, here is an example entry from the collection :

{
    "_id" : ObjectId("5b9551a60e89ad15a8ff77fb"),
    "name" : "XXX",
    "prenom" : "KEVIN",
    "datenaissance" : "17/11/2011",
    "mail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a010f1c03040a262b3a25393e2f642c38">[email protected]</a>",
    "tel" : "XXXXXXXXXX",
    "sexe" : "Male",
    "adresse" : "XXXXXXXX",
    "note" : [ 
        {
            "matiere" : "French",
            "note" : "10/20",
            "date" : "01/09/2018"
        }, 
        {
            "subject" : "English",
            "grade" : "07/20",
            "date" : "26/09/2018"
        }, 
        {
            "subject" : "Physical Education",
            "grade" : "15/20",
            "date" : "29/09/2018"
        }
    ]
}

I am looking to count the number of males and females present in the dataset so that I can represent it on my chart but I am unsure about the process.

Thank you for your help.

If I attempt to do this, my charts cannot find the variables countHomme and countFemme :

Javascript :

 app.get("/api/getUser",function(req,res){
    model.find({},function(err,data){
              if(err){
                  res.send(err);
              }
              else{
                  res.send(data);
                  var countHomme = model.where({ 'sexe': 'Male' }).count();
                  res.send(countHomme);
                  var countFemme = model.where({ 'sexe': 'Female' }).count();
                  res.send(countFemme);
                  }
          });
  })

Typescript :

 ngAfterViewInit() {
    this.canvas = document.getElementById('myChart');
    this.ctx = this.canvas.getContext('2d');
    let myChart = new Chart(this.ctx, {
      type: 'pie',
      data: {
          labels: ["Female", "Male"],
          datasets: [{
              label: '# of Votes',
              data: [countFemme, countHomme],
              backgroundColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)'
              ],
              borderWidth: 1
          }]
      },
      options: {
        responsive: false,
        display:true
      }
    });
  }

Answer №1

In my opinion, retrieving data on male and female sex from the backend using an API is more efficient. By utilizing mongoose ORM's Model.count() method, you can easily calculate the total counts and receive a JSON object tailored to your requirements. This data can then be seamlessly integrated into chart.js for visualization.

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

The function get() in p5.js will provide you with an array of pixels that is empty

I am currently working on a project that is inspired by this particular video. Within p5.js, I have been utilizing the get() function. My goal is to divide a large tileset into smaller images and store them in an array. However, I have encountered an issue ...

What is the process for crafting a Vuejs controlled input form?

Although I am familiar with creating controlled components in React using state, I am new to the Vue framework and would like to understand how to adapt my code from React to be compatible with Vue. My goal is to store the values of input fields in a data ...

JavaScript and HTML have encountered an Uncaught TypeError: The property 'addEventListener' cannot be read because it is null

Having an issue here. Whenever I try to play sound from an image, I encounter an error. Uncaught TypeError: Cannot read property 'addEventListener' of null Here is my HTML code: <html> <head> <title>Music</title> < ...

The outcome from using Array.reduce may not always match the expected result

After discovering an unexpected behavior in Typescript's type-inference, I suspect there may be a bug. Imagine having a list of the MyItem interface. interface MyItem { id?: string; value: string; } const myItemList: MyItem[] = []; It's ...

Restrict HTML Content in Json Result using PHP and Jquery

I'm currently working with a Controller that outputs JSON response and a JavaScript function that appends that response to the last tr in an HTML table. <pre> $reponse="<tr class=\"border_bottom\"><td>My Repo ...

The Google Visualization chart fails to display properly once CSS is applied

Struggling with a graph display issue here. It's quite perplexing as it works fine on older laptops and Safari, but not on Chrome or older versions of Firefox. Works like a charm on my old laptop and Safari, but fails on Chrome and Firefox (haven&apo ...

Halt the iteration once you reach the initial item in the array

I am encountering a challenge with this for loop. My goal is to extract the most recent order of "customers" and save it in my database. However, running this loop fetches both the failed order and the recent order. for (var i = 0; i < json.length; ...

Properties cannot be accessed using the standard method in the controller; however, they function correctly when using an arrow

Currently, I am facing a challenge where traditional class methods do not allow me to access the userService. I aim to write typical class methods in my user controller like this: public async register(req: Request, res: Response, next: NextFunction): Pr ...

gyp ALERT: Received a warning of EACCES when attempting to install angular/cli

Working on Ubuntu 17.04 with Node 8.9.4 LTS installed, I encountered an error loop while trying to install Angular CLI using npm. gyp WARN EACCES user "root" does not have permission to access the dev dir "/usr/lib/node_modules/@angular/cli/node_modules/n ...

Utilizing Interface Merging: Determining the Appropriate Instance Type for Field Types

I am in need of writing a definition file for an external library. I have augmented a class using interface merging and there are situations where a field of the library class is of the same type as the instance itself. Here is a snippet of demo code: // ...

How can I retrieve the handle for an item within a jQuery collection from within the success function of an .ajax() call?

I'm currently facing an issue with a jQuery ajax call that I have firing for each element in a collection identified by a specific jQuery selector. Here's a snippet of the code: $('.myClass').each(function () { $.ajax({ url ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Implementing a DataTable filter functionality using external buttons or links

I want to enhance the search functionality of my table by incorporating a treeview style set of buttons or links next to it. This is how I envision it: Take a look at this design: Here's where it gets tricky. When I click on a specific year, I want ...

The enigma of Angular Change Detection: Unraveling the relationship between child events and parent

I am striving to find a way to avoid triggering Change Detection in ancestor or parent components when a DOM click event is detected in a child component. It seems that this may not be achievable, as ancestors or parents of the child component will always ...

How can you display a border around a <td> element in an HTML table only when it contains data, using jQuery or JavaScript?

My HTML table consists of the following structure: <table class="table table-bordered"> <thead> <tr> <th>Tag</th> <th>Time Code</th> </tr> </thea ...

Angular2 encountered a TypeError stating that self._el_11 is not a valid function

Looking to attach an event listener to an input field? Check out the code snippet below: <input ref-search (keyup)="search(search.value)"> Here is the corresponding search method: search(condition: string){ console.log(condition); } When ente ...

Transfer an object for reusability in a different JavaScript file without utilizing the default operator

I have a scenario where I have two files organized in a tree structure that defines an object. The first file is called common.js. export default { table: { actions: { save: 'Save', delete: 'Delete', update: ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Delaying navigation to the next URL until a distinct category name is identified

Within this section of JSP code, I am implementing JavaScript and AJAX to validate the uniqueness of a category name. When the submit button is pressed for the first time, it prompts the user to enter a category name. Subsequently, an AJAX call is made to ...