NodeJS and mongoDb with mongoose

Hi - I am trying to view mongodb collections (just to view) in browser URL by accessing localhost:4000/books

app.js code:

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Book = require("./book.model");

var db = "mongodb://localhost:27017/example";
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });

const conSuccess = mongoose.connection
conSuccess.once('open', _ => {
  console.log('Database connected:', db)

conSuccess.on('error', err => {
  console.error('connection error:', err)

var port = 4000;
app.listen(port, function () {
  console.log("app listening on port " + port);
//REST get
app.get('/', function(req,res){
  res.send("happy to be here");

app.get('/books', function(req,res) {
  console.log("get all books");
  exec(function(err, books){
      res.send("error has occured");
    } else {


var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var BookSchema = new Schema({
  title: String,
  author: String,
  category: String,

module.exports = mongoose.model("book", BookSchema);

and the MongoDB server started in cmd prompt

ran> node app
the console displayed messages as
“app listening on port 4000
Database connected: mongodb://localhost:27017/example”

in URL

display erros as

refernceError: exec is not defined. why is that, please help on this issue.

Hey there,

what happens when you move your existing app.listen(...) to the bottom of your file?