3

So i have made an application using node.js and connected it to mongoDB, but no data is showing, it is simply showing and empty json data file []. The database name is sample_geospatial and the collection is named shipwrecks and all ip addresses are OK to connect with.

Why am i not succeeding with my task to show the data in the browser?

This is my 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 indexRouter = require('./routes/index');
var shipwrecksRouter = require('./routes/shipwrecks');

var app = express();

// Database connect with moongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://gockzor:***********@cluster0-boypg.azure.mongodb.net/test?retryWrites=true&w=majority');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
    console.log("Kopplingen lyckades!");
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

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('/shipwrecks', shipwrecksRouter);

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

This is my model

var mongoose = require('mongoose');

var WrecksSched = new mongoose.Schema({
    recrd: String,
    vesslterms: String,
    feature_type: String,
    chart: String,
    latdec: Number,
    londec: Number,
    gp_quality: String,
    depth: String,
    sounding_type: String,
    history: String,
    quasou: String,
    watlev: String,
    coordinates: Array,
}, {
    collection: 'shipwrecks'
});
module.exports = mongoose.model('ShipwrecksModel', WrecksSched);

This is my routes file

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

var mongoose = require('mongoose');
var ShipwrecksModel = require('../models/ShipwrecksModel.js');

router.get('/', function (req, res, next) {
    ShipwrecksModel.find(function (err, wrecks) {
        if (err) return next(err);
        else {
            res.json(wrecks);
        }
    });
});
module.exports = router;
4
  • 2
    Are you seeing the wrecks data if you log it to the console before sending with res.json? Commented Dec 13, 2019 at 18:20
  • 1
    If you're seeing [] in the api response rather than an error - then the issue could either be you're not able to connect to proper collection or proper db where your collections exists, So from your dburl you've got connected to test but is that your db where your collection shipwrecks exists ? If not the try to switch to actual db or replace test in url with actual db.. Commented Dec 13, 2019 at 18:43
  • 1
    Replace test in your mongoose url with your db name which is sample_geospatial Commented Dec 13, 2019 at 19:08
  • Thanks for the quick replys, it was that simple :) I copied the connection string directly from mongoDB, did not realise i had to specify the database in the url :) Commented Dec 13, 2019 at 19:51

1 Answer 1

3

Putting it as an answer :

If you're seeing [] in the api response rather than an error -

then the issue could either be you're not able to connect to proper collection name(if you're sure collection has data in it) or correct db where your collection exists.

So from your DB url :

'mongodb+srv://gockzor:***********@cluster0-boypg.azure.mongodb.net/test?retryWrites=true&w=majority'

You've got connected to test DB, So is that your DB where your collection shipwrecks exists ? If not the try to switch to actual DB after getting connected or replace test in url with actual DB name.

So by default you'll get an url w.r.t. to test db when you get it from Atlas mongoDB. So replace it on url once in all or you can switch it over the code after connecting to DB, using useDb function. Ex. :-

From code a basic way to switch DB ::

 async function myDbConnection() {

    const url = mongodb+srv://gockzor:***********@cluster0-boypg.azure.mongodb.net/test?retryWrites=true&w=majority';

    try {
        await mongoose.connect(url, { useNewUrlParser: true });
        console.log('Connected Successfully')
        mongoose.connection.useDb('myDB'); // Switching happens here..
        /**
         * Do some DB transaction with mongoose models as by now models has already been registered to created DB connection
         */
    } catch (error) {
        console.log('Error connecting to DB ::', error);
    }
}

Or you can have something like this directly in url ::

const dbUrl = mongodb+srv://gockzor:***********@cluster0-boypg.azure.mongodb.net/myDB?retryWrites=true&w=majority'
Sign up to request clarification or add additional context in comments.

Comments

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.