Home > Blockchain >  How do I use MongoDB data with D3 and Node?
How do I use MongoDB data with D3 and Node?

Time:09-18

Using Node, Express, Mongoose, and MongoDB, I'm trying to send a GET request to MongoDB and then use the data as an object for a D3 graph. I have the code for the graph in a separate js file. How do I send the data to that file?

Here are the basic Schemas I'm using:

var hikeSessionSchema = new mongoose.Schema({
    hike_name: {type: String, required: true},
    hike_date: {type: String, required: true},
    mileage: {type: Number, required: true},
    duration: {type: String, required: true},
    elevation_gain: {type: Number, required: true},
    city: {type: String, required: true},
    location: {type: String, required: true},
    notes: String
  })

var hikerSchema = new mongoose.Schema({
  username: {type: String, required: true},
  log: [hikeSessionSchema]
})

var HikeSession = mongoose.model('HikeSession', hikeSessionSchema)
var Hiker = mongoose.model('Hiker', hikerSchema)

So I want to find the user by ID, then get an array of the user's HikeSessions. And I want to move that data to a js doc to make a d3 graph (I've already made the d3 app on CodePen but connected it to Google Sheets before).

I think the GET request should be something like this, but I don't know what to do with the result. The path will probably change:

app.get('/:id', (req, res) => {
  const id = req.params.id;

  Hiker.findById(id)
  .then(result => {
    //What goes here?
  })
  .catch(err => {
    console.log(err);
  })
}

After I get the data into the d3 doc, I'm not sure what challenges I'll run into with rendering it.

CodePudding user response:

Step 1:

Define and export your d3_generator(input) function in d3.js:

const d3_generator = (input) => {
  
  /// (Your logic)

}

module.exports = { d3_generator };

Step 2

Import d3_generator function from d3.js in your controller and use it after you got result from MongoDB:

const { d3_generator } = require('./d3');

...

app.get('/:id', (req, res) => {
  const id = req.params.id;

  Hiker.findById(id)
  .then(result => {

    let generated_d3 = d3_generator(result.log);

  })
  .catch(err => {
    console.log(err);
  })
}

  • Related