Joakim Engqvist
Joakim Engqvist

Reputation: 121

Get data from mongoDB using node.js, connection works but no data is showing

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;

Upvotes: 3

Views: 2134

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17935

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'

Upvotes: 2

Related Questions