0

sry if this problem is a noob one(im new here)...

I've been trying to set up my app to connect to the db but im getting this error and I cant seem to find the problem.

This is the code

    const express = require('express');
    const app = express();
    const ejs = require('ejs');
    const path = require('path');
    const mongo = require('mongodb').MongoClient;
    const dbUrl = 'mongodb://localhost:3000/contractformapp';
    const bodyParser = require('body-parser');
    const ObjectId = require('mongodb').ObjectId;

    mongo.connect(dbUrl, function(err, contract) {
        if (err) {
            console.log("Error connecting to the database");
        } else {
            console.log("Connection to database was successful");
            contracts = contract.db('contractformapp').collection('contracts');
        }
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));



    app.get('/', function (req, res) {
        contracts.find({}).toArray(function (err, docs) {
            if (err) {
                console.log(err);
                return;
            }
            res.render('index', { docs: docs });
        });
    });


app.listen(3000, 'localhost', (err) => {
    if (err) {
        console.log('err');
    } else {
        console.log('Server started listening');
    }
});


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

And when i try to run nodemon and open http://localhost:3000/

Server started listening
Error connecting to the database
ReferenceError: contracts is not defined
Arlind
  • 347
  • 2
  • 15
  • Your call to connect is incorrect: https://docs.mongodb.com/manual/reference/method/connect/. (really wasn't that hard to google) – Randy Casburn May 12 '18 at 00:00

1 Answers1

0

Your mongo server shouldn't be on the same port as your express server. The default for mongdb is 27017 I think, so that's probably where it is.

const dbUrl = 'mongodb://localhost:27017/contractformapp';

That, and make sure your mongodb is up and running.

Kevin
  • 359
  • 2
  • 7
  • 22