Apologies if this issue seems like a beginner one (I'm new to this platform)...
I've been attempting to configure my application to connect to the database, but I keep encountering an error and I can't pinpoint the problem.
Here's the code snippet:
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 the 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');
When I try to execute nodemon and visit http://localhost:3000/
Server started listening
Error connecting to the database
ReferenceError: contracts is not defined