0

I am building a small boat visualizer using AIS APIs. 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: [NAME, CALLSIGN, HEADING, SOG, IMO, MMSI, LONGITUDE, LATITUDE, DATE]. I can correctly connect to MongoDB as I sudo npm start.

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.

The problem: I would like to send also the API data to a collection to MongoDB database. I successfully connect to MongoDB but information are not being passed. I don't understand why that is happening despite following official documentation on forming a Schema is followed. Below is how I try to write to MongoDB:

users.js

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();
});

LatitudeLongitude.js --> forming a Schema

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;

app.js

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(() => console.log('MongoDB Connection established'))
    .catch((err) => 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) => {
    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;

Also below is my collection for completeness:

collection

what I have done so far:

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.

I believe that the file users.js should be the one that is probably missing something. The connection to the database happens on the file app.js and I can confirm that the I can successfully connect to MongoDB.

I consulted this source, and also this one. But none of them was useful to understand what I am doing wrong.

Emanuele
  • 2,194
  • 6
  • 32
  • 71
  • have you tried logging the properties you are destructuring from `req.body` to make sure you are getting the correct data in the request body? – Yousaf Jun 01 '20 at 13:33
  • @Yousaf, thanks for stopping by and reading the question. No I didn't, could you please help me with that? Your time is very appreciated! :) – Emanuele Jun 01 '20 at 13:36
  • try logging the properties to console and make sure you are receiving the data on the server. – Yousaf Jun 01 '20 at 13:37
  • you mean to try `console.log('req.body');`? – Emanuele Jun 01 '20 at 13:42
  • i mean `console.log(name)` or `console.log(callsign)` ... – Yousaf Jun 01 '20 at 13:43
  • Try this API in POSTMAN see to it that you getting expected response if yes then kindly attach your code snippet where you're making API from front-end – Sagar Pednekar Jun 01 '20 at 14:03
  • Thanks for reading the question @SagarPednekar, I don't know how to use POSTMAN. I will have to spend some time to understand it. I was trying to see if it was possible to solve it with the information I have so far. Any other possibilities? – Emanuele Jun 01 '20 at 15:49

0 Answers0