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;
wrecksdata if you log it to the console before sending withres.json?[]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 yourdburlyou've got connected totestbut is that your db where your collectionshipwrecksexists ? If not the try to switch to actual db or replace test in url with actual db..