Basically, I am trying to fetch data from MongoDB collection and read it with d3.json
.
First, I sent data to a specific route in main index.js
.
// fetch data
app.get('/fetch.json', (req, res) => {
Data.find({})
.then(sample => {
res.json(sample)
})
})
If I check localhost:3000/fetch.json
, my data
is in there as an array with each object.
[{...},{...},{...},{...}]
However, when I tried to read data with d3
, I got a Syntax Error
:
Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0
This is the code that attempts to read data:
// load data
d3.json('./fetch.json', (err, data) => {
if (err) {
throw err
}
data.map((t) => {
console.log(t)
})
})
I tried different approaches, considering this answer: Convert Mongoose docs to json. However, I got the same result.
Am I missing something inside main index.js
or I need to fetch data in a different way?