title: ReactJS - JavaScript: Failing to dynamically pass API data to MongoDB database
body: <p>I am building a small boat visualizer using <a href="https://api.vesselfinder.com/docs/vesselslist.html" rel="nofollow noreferrer">AIS APIs</a>. After inquiring the APIs I am able to obtain a json file with the vessels and filter with only the vessel I am interested in, and inject them into a table on the webpage. The API gives several fileds but I only filter specific ones: <code>[NAME, CALLSIGN, HEADING, SOG, IMO, MMSI, LONGITUDE, LATITUDE, DATE]</code>. I can correctly connect to MongoDB as I <code>sudo npm start.</code></p>
  
  <p>Please shed light on why information are not being saved. I followed the documentation and a lot of posts but still something is not right. </p>
  
  <p><strong>The problem:</strong> I would like to send also the API data to a collection to <code>MongoDB</code> database. I successfully connect to <code>MongoDB</code> but information are not being passed. I don't understand why that is happening despite following <a href="https://docs.mongodb.com/manual/core/schema-validation/" rel="nofollow noreferrer">official documentation on forming a Schema</a> is followed.
  Below is how I try to write to <code>MongoDB</code>:</p>
  
  <p><strong>users.js</strong></p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  
  const LatitudeLongitude = require('../models/LatitudeLongitude');
  
  /* GET users listing. */
  router.get('/', function(req, res, next) {
      res.send('respond with a resource');
  });
  
  
  router.post('/vessles/map/latlng', function(req, res) {
      const { name, callsign, heading, sog, imo, mmsi, longitude, latitude, date } = req.body;
      let errors = [];
      // Check required fields
      if (!name || !callsign || !heading || !sog || !imo || !mmsi || !longitude || !latitude || !date) {
          errors.push({ msg: 'No data received' });
          console.log('error');
      }
      // vessel exists
      const newVessel = new LatitudeLongitude({
          name,
          callsign,
          heading,
          sog,
          imo,
          mmsi,
          longitude,
          latitude,
          date
      });
      // Save all vessels info
      newVessel.save(function(err, vessel) {
          if (err) return console.log(err);
      });
      res.status(200).end();
  });
  </code></pre>
  
  <p><strong>LatitudeLongitude.js</strong>  -->  forming a Schema</p>
  
  <pre><code>const mongoose = require('mongoose');
  
  const LatitudeLongitudeSchema = new mongoose.Schema(
      {
          name: {
              type: String,
              required: true
          },
          callsign: {
              type: String,
              required: true
          },
          heading: {
              type: Number,
              required: false
          },
          sog: {
              type: Number,
              required: true
          },
          imo: {
              type: Number,
              required: false
          },
          mmsi: {
              type: Number,
              required: false
          },
          longitude: {
              type: Number,
              required: false
          },
          latitude: {
              type: Number,
              required: false
          },
          date: {
              type: Date,
              required: true
          }
      },
      { collection: 'latitudelongitude' }
  );
  const LatitudeLongitude = mongoose.model('LatitudeLongitude', LatitudeLongitudeSchema);
  module.exports = LatitudeLongitude;
  </code></pre>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>var createError = require('http-errors');
  var express = require('express');
  var path = require('path');
  var cookieParser = require('cookie-parser');
  var logger = require('morgan');
  var cors = require('cors');
  
  var indexRouter = require('./routes/index');
  var usersRouter = require('./routes/users');
  
  var mongoose = require('mongoose');
  const bodyParser = require('body-parser');
  require('./config/keys');
  
  var app = express();
  app.use(cors());
  app.options('*', cors());
  
  // DB Config
  const db = require('./config/keys').MongoURI;
  
  const options = {
      useNewUrlParser: true,
      reconnectTries: Number.MAX_VALUE,
      poolSize: 10
  };
  
  mongoose
      .connect(db, options)
      .then(() =&gt; console.log('MongoDB Connection established'))
      .catch((err) =&gt; console.log('Error connecting MongoDB database due to: ', err));
  
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'jade');
  
  // Bodyparser
  app.use(express.urlencoded({ extended: false }));
  
  app.use(logger('dev'));
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  
  app.use('/', indexRouter);
  app.use('/users', usersRouter);
  
  app.use((req, res, next) =&gt; {
      res.header('Access-Control-Allow-Origin', '*');
      next();
  });
  
  const PORT = process.env.PORT || 3000;
  
  app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
  app.use(bodyParser.json({ limit: '50mb' }));
  app.use(cors());
  
  app.listen(PORT, console.log(`Server started on port ${PORT}`));
  
  module.exports = app;
  </code></pre>
  
  <p>Also below is my collection for completeness:</p>
  
  <p><img src="https://i.imgur.com/g7kks16.png" alt="collection"></p>
  
  <p><strong>what I have done so far:</strong></p>
  
  <p>I tried many different ways to pass data from the API to MongoDB and the best approach I found simple is the one above I posted, but there is an error I can't seem to catch.</p>
  
  <p>I believe that the file <code>users.js</code> should be the one that is probably missing something.
  The connection to the database happens on the file <code>app.js</code> and I can confirm that the I can successfully connect to <code>MongoDB</code>. </p>
  
  <p>I consulted <a href="https://stackoverflow.com/questions/50732600/how-to-pass-form-data-to-mongodb-in-react">this source</a>, and also <a href="https://stackoverflow.com/questions/50617351/react-post-requests-with-express-node-and-mongodb">this one</a>. But none of them was useful to understand what I am doing wrong.</p>