What to Require in Your JS File For an Express App Using EJS and Mongoose/MongoDB

In your project directory, run npm init. Add the details as you'd like.

Then in your terminal, run:

$ npm i mongoose
$ npm install ejs-mate --save
$ npm install express --save

Copy this at the top of app.js

const express = require('express');
const app = express();
const path = require('path');
const ejsMate = require('ejs-mate');
const mongoose = require('mongoose');

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.set('views', path.join(__dirname, 'views' ))
app.set('view engine', 'ejs')

mongoose.connect('mongodb://localhost:27017/{dbnamehere}')
.then(() => {
    console.log('Connection open')
})
.catch(err => {
    console.log(err)
    console.log('Oh no! Error.')
})

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

app.get('/', (req, res) => {
    res.render('home')
})

app.listen(3000, () => {
    console.log('Listening')
})

Now, run nodemon app.js or node app.js to start your server and open your localhost.

Subscribe to The Bookshelf

It's one email a week sharing what I'm thinking about and fascinating things I found on the internet.
albert@einstein.com
Subscribe