简体   繁体   中英

Nodejs Registration form not saving to mongodb database

I'm new to this and am following a tutorial. I can't seem to get my form to save in the database. Everything seems to be working fine and I am not getting any error messages. I see the form input in the console log - and strangely enough, the console log has automatically assigned mongodb ID's. For example, '_id: 605a8ab5b7xxxxxxx'

Would appreciate any assistance.

Model User.js

const mongoose = require('mongoose')


const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }, 
    email: {
        type: String,
    },
    password: {
        type: String
    },
    userType: {
        type: String,
        required: true,
        default: 'Tester',
        enum: ['Tester', 'Admin']
    },
    date: {
        type: Date,
        default: true
    }
})

const User = mongoose.model('User', UserSchema);
module.exports = User;

routes users.js

const express = require('express')
const router = express.Router();
const bcrypt = require('bcryptjs');

// User model
const User = require('../models/User');

// Login Page
router.get('/login', (req, res) => res.render('login'));

// Register Page
router.get('/register', (req, res) => res.render('register'));

// Register Handle
router.post('/register', (req, res) => {
    const { name, email, password, password2, userType } = req.body;

    let errors = [];

    // Check required fields
    if(!name || !email || !password || !password2 || !userType){
        errors.push({ msg: 'Please fill in all fields'})
    }

    // Check if passwords match
    if(password !== password2) {
        errors.push({ msg: 'Passwords do not match' });
    }

    // Check password length
    if(password.length < 12) {
        errors.push({ msg: 'Password should be at least 12 characters long' });
    }

    if(errors.length > 0) {
        res.render('register', {
            errors,
            name,
            email,
            password,
            password2,
            userType
        })
    } else {
        // Passed Validation
        User.findOne({ email: email })
            .then(user => {
                if(user) {
                    // User exists
                    errors.push({ msg: 'Email already registered' });
                    res.render('register', {
                        errors,
                        name,
                        email,
                        password,
                        password2,
                        userType
                    })
                } else {
                    const newUser = new User({
                        name,
                        email,
                        password,
                        userType
                    });
                    
                    console.log(newUser)
                    res.send('hello');
                }
            })
    }
})

module.exports = router;

index.js

const express = require('express')
const router = express.Router();

router.get('/', (req, res) => res.render('welcome'));

module.exports = router;

views register.ejs

<div class="row mt-5">
    <div class="col-md-6 m-auto">
      <div class="card card-body">
        <h1 class="text-center mb-3">
          <i class="fas fa-user-plus"></i> Register
        </h1>
        <%- include ("./partials/messages") %>
        <form action="/auth/register" method="POST">
          <div class="form-group">
            <label for="name">Name</label>
            <input
              type="name"
              id="name"
              name="name"
              class="form-control"
              placeholder="Enter Name"
              value="<%= typeof name != 'undefined' ? name : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input
              type="email"
              id="email"
              name="email"
              class="form-control"
              placeholder="Enter Email"
              value="<%= typeof email != 'undefined' ? email : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input
              type="password"
              id="password"
              name="password"
              class="form-control"
              placeholder="Create Password"
              value="<%= typeof password != 'undefined' ? password : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="password2">Confirm Password</label>
            <input
              type="password"
              id="password2"
              name="password2"
              class="form-control"
              placeholder="Confirm Password"
              value="<%= typeof password2 != 'undefined' ? password2 : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="name">User Type</label>
            <input
              type="userType"
              id="userType"
              name="userType"
              class="form-control"
              placeholder="Enter User Type"
              value="<%= typeof userType != 'undefined' ? userType : '' %>"
            />
          </div>
          <button type="submit" class="btn btn-primary btn-block">
            Register
          </button>
        </form>
        <p class="lead mt-4">Have An Account? <a href="/auth/login">Login</a></p>
      </div>
    </div>
  </div>

partials messages.ejs

<% if(typeof errors != 'undefined') { %>
    <% errors.forEach(function(error) { %>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <%= error.msg %>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
          </div>
    <% }); %>
<% } %>

https://mongoosejs.com/docs/models.html#constructing-documents

By calling new User(({.. }) , you are creating an instance of the document, you must call save inorder to save the Instance in the DB.

const newUser = new User({ name, email, password, userType });

newUser.save(function(err,result){
    if (err){
        console.log(err);
    }
    else{
        console.log(result)
    }
})

Or You can use - Model.create
 User.create({ name, email,password, userType }, function (err, d) { if (err) return handleError(err); // });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM