'Reading Data in From MongoDB through Nodejs and displaying it through D3 Visualization in Angular
I am trying to create a bar graph by reading data from my MongoDB collection through Node js and then feeding it through D3.js in Angular. I am not sure how to connect the Node js and D3.js in Angular to feed the MongoDB data.
This is my code in Angular:
ngOnInit(): void {
this.createSvg();
d3.json('http://localhost:4200/chart').then((data: any) => this.drawBars(data));
}
This is my code in Node js:
const PORT = 4200;
//required installations
const axios = require('axios')
const express = require('express');
const res = require('express/lib/response');
const app = express();
const path = require('path');
const { MongoClient, ServerApiVersion } = require('mongodb');
/* This is where the Angular files live after they are built. */
app.use(express.static(path.join(__dirname, './d3/dist/d3')));
var http = require('http').Server(app);
app.get('/chart', async function(req, res) {
await client.connect();
const database = client.db("lab6");
const coll = database.collection("player_stats");
coll.find({}, { projection: { _id: 0, first_name: 1, last_name: 1 }}).toArray(function(err, result){
if (err) throw err;
console.log(result);
});
})
app.listen(PORT, () => {
console.log('Listening on *:4200');
});
This Angular code is based on this site: https://blog.logrocket.com/data-visualization-angular-d3/
The data is not displaying in the bar graph and I am getting a blank page.
drawBars function:
private drawBars(data: any[]): void {
// Create the X-axis band scale
const x = d3.scaleBand()
.range([0, this.width])
.domain(data.map(d => d.Framework))
.padding(0.2);
// Draw the X-axis on the DOM
this.svg.append("g")
.attr("transform", "translate(0," + this.height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end");
// Create the Y-axis band scale
const y = d3.scaleLinear()
.domain([0, 200000])
.range([this.height, 0]);
// Draw the Y-axis on the DOM
this.svg.append("g")
.call(d3.axisLeft(y));
// Create and fill the bars
this.svg.selectAll("bars")
.data(data)
.enter()
.append("rect")
.attr("x", (d: any) => x(d.Framework))
.attr("y", (d: any) => y(d.Stars))
.attr("width", x.bandwidth())
.attr("height", (d: any) => this.height - y(d.Stars))
.attr("fill", "#d04a35");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
