2023-03-30

Change User Email in MongoDB via Web App created with Node, Express, EJS, and Mongoose

I have a simple blogging web application. I have set up the ability for users to log in and I am now working on account management. The first part of the account management will be for users to change their email.

I have an account.ejs page that includes a nav.ejs, displays the email of the currently logged in user, and then a form for which the user can update their email.

The form is simple, it asks for the new email and then includes a second text box to confirm their changed email, and these text boxes must match to proceed.

Here is where I am having trouble - I have a signup.ejs page with a form.addEventListener that handles input into a form, and if all is well, I use a res = await fetch() to send to an authRoutes.js which in turn, is handled by an authController.js

I am trying to adjust my account.ejs page such that it contains a form allowing a user to update their email in my MongoDB. I am never able to move from the form inside account.ejs to my accountPost method inside authController unless I changed the variable name of const form = document.querySelector('form'); to const form2 = document.querySelector('form');

My authController.js will then update the User's email in MongoDB if I adjust the form variable to form2, within the document.querySelector('form'); I am having trouble understanding why this is and what I am doing wrong.

account.ejs:

<html lang="en">
<%- include("./partials/head.ejs") %>

<body>
  <%- include("./partials/nav.ejs") %>

  <div class="account content">
    <div>
      <h2 class="management-header">Account Management for <%= user.email %></h2>
    </div>
    <div class="alter-email content">
        <p>Change Email</p>
        <hr>
        <form class="alter-email-form" action="/account/<%= user._id %>" method="POST">
          <label for="oldEmail">Old Email</label>
          <input type="text" id="oldEmail" name="oldEmail" required>
          <label for="newEmail">New Email</label>
          <input type="text" id="newEmail" name="newEmail" required>
          <button>Update Email</button>
        </form>
      </div>

  </div>

  <%- include("./partials/footer.ejs") %>

  <script>
    //THIS IS THE PROBLEM
    const form2 = document.querySelector('form');
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        //get values
        const oldEmail = form.oldEmail.value;
        const newEmail = form.newEmail.value;
        try {
            const res = await fetch('/account', {
                method: 'POST',
                body: JSON.stringify({ oldEmail, newEmail }),
                headers: { 'Content-Type': 'application/json' }
            });
            const data = await res.json();
            console.log(data);
            if(data.user) {
                location.assign('/blogs');
            }
        }
        catch (err) {
            console.log(err);
        }        
    });
  </script>
</body>
</html>

accountPost in authController.js:

const accountPost = async (req, res) => {    
    const id = req.params.id;
    const {newEmail, oldEmail} = req.body;
    console.log(newEmail, oldEmail);
    let user = await User.findById(id);
    user.updateOne({
        '_id': id,
        'email': newEmail
    })
    .then(result => {
        res.redirect('/');
    })
}

module.exports = {
    accountPost
}

app.js

const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const blogRoutes = require('./routes/blogRoutes');
const authRoutes = require('./routes/authRoutes');
const cookieParser = require('cookie-parser');
const { checkUser } = require('./middleware/authMiddleware');
require('dotenv').config();

//express app
const app = express();

//mongoDB connection string
const dbURI = `mongodb+srv://${process.env.blog_username}:${process.env.blog_password}@nodecourse.h4qkmfb.mongodb.net/nodeCourse?retryWrites=true&w=majority`;

mongoose.connect(dbURI)
    .then((result) => app.listen(3000))
    .catch((err) => console.log(err));

//register view engine
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.redirect('/blogs');
});

app.get('/about', (req, res) => {
    res.render('about', { title: 'About'});
});

app.use(authRoutes);

//404 page
app.use((req, res) => {
    res.status(404).render('404', {title: '404'});
})


No comments:

Post a Comment