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:
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.