I'm using node.js to code a simple login/ sign up program that stores the account details (username, email, and password) on a MongoDB database. I've made sure I've downloaded MongoDB correctly, but I can't figure out what's wrong with my code... there are no errors thrown but the name, email, and hashedPassword aren't being inserted into the users database.
Here's my code from my server.js file:
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')
const userArray = [];
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose'))
const initializePassport = require('./passport-config')
initializePassport(
passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
)
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.get('/', checkAuthenticated, (req, res) => {
res.render('index.ejs', { name: req.user.name })
})
app.get('/login', checkNotAuthenticated, (req, res) => {
res.render('login.ejs')
})
app.post('/login', checkNotAuthenticated, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}))
app.get('/register', checkNotAuthenticated, (req, res) => {
res.render('register.ejs')
})
//**THE PROBLEM IS SOMEWHERE HERE I THINK**
app.post('/register', checkNotAuthenticated, async (req, res) => {
console.log("Before try")
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
console.log("Password hashed")
userArray.push({
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
console.log("pushed to array")
db.users.insertOne({
"name": req.body.name,
"email": req.body.email,
"password": hashedPassword
})
console.log("New user loaded to DB!")
console.log(req.body.name);
console.log(req.body.email);
console.log(hashedPassword);
res.redirect('/login')
} catch {
res.redirect('/register')
}
})
app.delete('/logout', (req, res) => {
req.logOut()
res.redirect('/login')
})
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect('/login')
}
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return res.redirect('/')
}
next()
}
app.listen(3000)
I'm having the issue on the app.post('/register', checkNotAuthenticated, async (req, res) => {} part
I logged each step line of it and this is what comes up in the console:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Connected to Mongoose
Before try
Password hashed
pushed to array
So, as you can see, everything works except for inserting the user info into the database (I also know that because running db.users.find() in the Mongo shell returns nothing)... please help :'(