1

I am building a boat visualizer using AISHub APIs. After inquiring the APIs I am able to obtain a json file with the vessels I am interested in and inject these vessels inside a table.

the problem I have is that after I receive and filter the data from the API, I would like to send them to MongoDB to store them. As of now MongoDB is not receiving any data and I don't know why?

According to the official documentation of MongoDB here is what I did to create the database: After hitting connect to my application as shown below and copy/paste the key:

connection

mongodb+srv://<username>:<password>@vessel-tracker-cluster-x2lpw.mongodb.net/test?retryWrites=true&w=majority

Below is how my cluser is organized:

cluster

And after accessing the collections you can see how the database is structured:

db

app.js

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

const PORT = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(cors());

app.route('/vessels/all').get(vesselController.getBaseAll);
app.route('vessels/:id/track').get(vesselController.getCurrent);
app.route('/vessels').get(vesselController.getHistory);

app.listen(PORT, console.log(`Server started on port ${PORT}`));

module.exports = app;

index.js

var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();

let hitCount = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

const mmsiOfInterest = [
    '367029520',
    '366909730',
    '367128570'
];

const shipNamesOfInterest = [
    'MICHIGAN',
    'JP BOISSEAU',
    'DELAWARE BAY
];

router.get('/hello', async function(req, res, next) {
    const cData = myCache.get('cData');

    if (!cData) {
        hitCount++;
        console.log(`hit ${hitCount} number of times`);
        const { data } = await axios.get(
             'http://data.aishub.net/ws.php?username=request'
        );
        const [ metaData, ships ] = data;
        const shipsOfInterest = ships.filter(
            (ship) => mmsiOfInterest.includes(ship.MMSI) || shipNamesOfInterest.includes(ship.NAME)
        );

        myCache.set('cData', shipsOfInterest, 70);
        res.send(data);
        return;
    }
    res.send(cData);
});

module.exports = router;

users.js

var express = require('express');
var router = express.Router();

// vessel models
const Vessles = require('../models/Vessels');

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});

router.post('/vessles/map', function(req, res) {
    const { callsign, name, imo, mmsi } = req.body;
    let errors = [];

    // Check required fields
    if (!callsign || !name || !imo || !mmsi) {
        errors.push({ msg: 'No data received' });
    }
    if (
        Vessles.findOne({ mmsi: mmsi }).then((vessels) => {
            if (vessels) {
                // vessel exists
                const newVessel = new Vessles({
                    callsign,
                    name,
                    imo,
                    mmsi
                });
            }
        })
    );
});

module.exports = router;

MondoDB Schema organization for Vessels.js

const mongoose = require('mongoose');

const VesselsSchema = new mongoose.Schema({
    callsign: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    imo: {
        type: Number,
        required: false
    },
    mmsi: {
        type: Number,
        required: false
    }
});

const Vessels = mongoose.model('Vessels', VesselsSchema);
module.exports = Vessels;

Posts that I have been reading to help me solve the problem but without success:

1) front end react is not sending data to db

2) connection to mongo db in react

3) This source was very useful but does not quite operate what I am trying to solve as it is more for rendering. Will surely be useful later though.

4) I thought that this source was extremely useful but didn't fully and clearly explain the process, otherwise with more explanation would probably be good.

Thanks for pointing in the right direction for solving this problem.

8
  • Check mongodb status it is Active or not. Commented Feb 12, 2020 at 17:21
  • Hello @AnkitKumarRajpoot, and thanks for reading the question. What do you mean? How do I check that? Commented Feb 12, 2020 at 17:34
  • Check connectivity is stable or not connect via terminal. Commented Feb 12, 2020 at 17:38
  • Hi @Emanuele what the version of Node.js you choose in Mongodb atlas? In Connect to Cluster in mongo db Atlas try select Node.JS version 2.2.12 or later Commented Feb 12, 2020 at 17:57
  • Hi @GabrielRodriguesSegalla, I first "Connect your Application" and second copy/past the connection string. My node version is v12.15.0 Commented Feb 12, 2020 at 18:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.