Not submit data in mongodb database - javascript

Here i tried to store form data in my mongodb database(mongodb compass).
but after submit when i check than there are nothing in my database.
when i press sign up button than it's show me just curly brackets.
App.js file(main file)
const express = require("express");
const app = express();
const port = 8081;
require('./db/conn');
const path = require("path");
const hbs = require("hbs");
const register = require("./models/register");
const static_path = path.join(__dirname,"../public");
const template_path = path.join(__dirname,"../templates/views");
const partials_path = path.join(__dirname,"../templates/partials");
app.set("views",template_path);
app.set("view engine","hbs");
hbs.registerPartials(partials_path);
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.get("/",(req,res)=>{
res.render("signup");
})
app.get("/signup",(req,res)=>{
res.render("index");
})
app.get("/register",(req,res)=>{
res.render("register");
})
app.post("/register",async(req,res)=>{
try{
const password = req.body.password;
const cpassword = req.body.cpassword;
if(password===cpassword){
const registerEmployee = new Register({
firstname : req.body.firstname,
lastname : req.body.lastname,
email : req.body.email,
phone : req.body.phone,
age : req.body.age,
password: req.body.password,
})
const registered = await registerEmployee.save();
console.log(registered);
}
else{
res.send("password not matched");
}
res.send(registered);
}catch(error){
res.status(404).send(error)
}
})
app.listen(port,()=>{
console.log("succesfully port");
})
register.js file(here i define mongoose.schema file)
const mongoose = require("mongoose");
const employeeSchema = mongoose.Schema({
firstname :{
type:String,
required:true,
},
lastname:{
type:String,
required:true,
},
email:{
type:String,
required:true,
unique:true,
},
phone:{
type:Number,
required:true,
unique:true,
},
age:{
type:Number,
required:true,
},
password:{
type:String,
required:true,
},
})
const Register = new mongoose.model("register",employeeSchema);
module.exports = Register;
signup.hbs file(html form)
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/signin.css">
<title>Create New Account</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous">
</script>
<div class="signin-form">
<form action="/register" method="POST">
<div class="form-header">
<h2>Sign Up</h2>
<h2>Fill out this form and start chatting with your friends.</h2><br>
</div>
<div class="form-group">
<br>
<lable>firstname</lable>
<input type="text" class="form-control" name="firstname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>lastname</lable>
<input type="text" class="form-control" name="lastname" placeholder="Username" />
</div>
<div class="form-group">
<br>
<lable>email Address</lable>
<input type="text" class="form-control" name="email" placeholder="someone#site.com" />
</div>
<div class="form-group">
<br>
<lable>phone Number</lable>
<input type="text" class="form-control" name="phone" placeholder="contact number" />
</div>
<div class="form-group">
<br>
<lable>Age</lable>
<input type="number" class="form-control" name="age" placeholder="age" />
</div>
<div class="form-group">
<label> Password </label>
<input type="text" class="form-control" name="password" placeholder="password" />
</div>
<div class="form-group">
<label>Confirm Password </label>
<input type="text" class="form-control" name="cpassword" placeholder="confirm password" />
</div>
<input type="checkbox" class="checkbox-inline" /> <label>i accept terms and condition</label>
<div class="form-group">
<button class="btn btn-primary btn-block btn-lg " name="sign_up">Sign_Up</button>
</div>
</form>
<div class="text-center small" style="color:#67428B;"> Already have an Account ?Login </div>
</div>
</body>
</html>

try to put new before mongoose.Schema :
const employeeSchema = new mongoose.Schema

after so much time i solved error successfully, so i think i want to write here
here you can see in app file 7th line
const register = require("./models/register");
and when i enter new data then i use Register instead of register so there are an error.
const registerEmployee = new Register

Related

how to insert array of objects in mongodb using express js

i want to insert my form data as an array of multiple objects.
how can i acheive this ..?
in below code only one object is inserted but i want to insert multiple objects that was described in mongoose schema.
i research a lot to do this but cant get success. please help me to acheive this.
i already acheive this in php but unable to do this in express.
[here is the code][1]
My Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css" integrity="sha512-XWTTruHZEYJsxV3W/lSXG1n3Q39YIWOstqvmFsdNEEQfHoZ6vm6E9GK2OrF6DSJSpIbRbi+Nn0WDPID9O7xB2Q==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/js/bootstrap.bundle.min.js" integrity="sha512-9GacT4119eY3AcosfWtHMsT5JyZudrexyEVzTBWV3viP/YfB9e2pEy3N7WXL3SV6ASXpTU0vzzSxsbfsuUH4sQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/js/bootstrap.min.js" integrity="sha512-8Y8eGK92dzouwpROIppwr+0kPauu0qqtnzZZNEF8Pat5tuRNJxJXCkbQfJ0HlUG3y1HB3z18CSKmUo7i2zcPpg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<script>
function remove_more(id) {
alertify.confirm('One Point ', 'Are you sure want to delete !', function () {
$('#box' + id).fadeOut(600, function () {
$('#box' + id).remove();
});
}, function () {
alertify.error('Cancel')
});
}
</script>
<div class="container my-5">
<form action="/add" method="post">
<input type="text" name="name" id="">
<input type="email" name="email" id="">
<div id="attributeBox" class="mb-3">
<div class="form-group row">
<div class="col-sm-5">
<label for="price" class="col-sm-3 control-label col-form-label">Price</label>
<input type="text" class="form-control" name="price[]" id="price">
</div>
<div class="col-sm-5">
<label for="qty" class="col-sm-3 control-label col-form-label">Qty</label>
<input type="text" class="form-control" name="qty[]" id="qty">
</div>
<div class="col-sm-2 mt-4 d-flex-align-item-center ">
<button type="button" id="Addattribute" class="btn btn-warning btn-sm"><i
class="fa fa-plus"></i></button>
</div>
</div>
</div>
<input type="hidden" id="numattribute" value="1">
<input type="submit" value="Submit">
</form>
</div>
<script>
$('#Addattribute').click(function (e) {
e.preventDefault();
var numattribute = jQuery('#numattribute').val();
numattribute++;
jQuery('#numattribute').val(numattribute);
var html1 = '<div id="box' + numattribute + '"><div class="form-group row"><div class="col-sm-5"><label for="price" class="col-sm-3 control-label col-form-label">Price</label><input type="text" class="form-control" name="price[]" id="price"></div><div class="col-sm-5"><label for="qty" class="col-sm-3 control-label col-form-label">Qty</label><input type="text" class="form-control" name="qty[]" id="qty"></div><div class="col-sm-2 mt-4 d-flex-align-item-center "><button type="button" id="Addattribute" class="btn btn-danger btn-sm float-right" onclick="remove_more(' + numattribute + ')"><i class="fa fa-trash"></i></button></div></div></div>'
jQuery('#attributeBox').append(html1);
});
</script>
</body>
</html>
mongoose schema
const mongoose = require("mongoose");
const { Schema } = mongoose;
const usersSchema = new Schema({
name: {
type: String,
required: [true, "Name is Required"],
},
email: {
type: String,
required: [true, "Email is Required"],
},
attributes: [
{
qty: { type: String, default: 1 },
price: { type: String, default: 1 },
},
],
created: {
type: Date,
required: true,
default: Date.now,
},
});
const user = mongoose.model("user", usersSchema);
user.createIndexes();
module.exports = user;
Add User API post
router.post("/add", urlencodedParser, async (req, res, next) => {
// An array of keys
var keys = req.body.qty;
// An array of values
var values = req.body.price;
// Map created
var map = new Map();
// Using loop to insert key
// value in map
for (var i = 0; i < keys.length; i++) {
map.set(keys[i], values[i]);
}
// Printing
for (var key of map.keys()) {
console.log(key + " => " + map.get(key));
}
const user = new User({
name: req.body.name,
email: req.body.email,
attributes: [
{
qty: key,
price: map.get(key),
},
],
});
console.log(user);
await user.save((err) => {
if (err) {
res.json({ message: err.message, type: "error" });
} else {
res.redirect("/");
}
});
});
my form has multiple fields

I keep getting Error: ER_EMPTY_QUERY: QUERY was empty

I'm trying to make a register page. When I enter the data that needs to be registered, it shows up on the console followed by Error: ER_EMPTY_QUERY.
I believe the problem is in the controllers/auth.js file but I can't figure it out for some reason. Please help, been stuck on this for the past 2 days.
controllers/auth.js:
const mysql = require('mysql');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'practice'
})
exports.register = (req, res) => {
console.log(req.body)
const {name, email, password, passwordConfirm} = req.body
db.query('SELECT email FROM users WHERE email = ?' [email], async (error, results) => {
if(error) {
console.log(error)
}
if( results.length > 0 ) {
return res.render('register', {
message: 'That email is already is use'
})
} else if( password !== passwordConfirm) {
return res.render('register', {
message: 'Passwords do not match'
})
}
let hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', {name: name, email: email, password: hashedPassword}, (error, results) => {
if(error) {
console.log(error)
} else {
console.log(results);
return res.render('register', {
message: 'User registered'
})
}
})
})
}
register.hbs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles.css">
<title>Document</title>
</head>
<body>
<nav>
<h4>Node MySQL</h4>
<ul>
<li>Home</li>
<li>Login</li>
<li>register</li>
</ul>
</nav>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Register Form
</div>
<div class="card-body">
<form action="/auth/register" method="POST">
<div class="mb-3">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="mb-3">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="mb-3">
<label for="passwordConfirm">Confirm Password</label>
<input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
{{#if message}}
<h4 class="alert alert-daner mt-4">{{message}}</h4>
{{/if}}
</div>
</body>
</html>

How to handle button click and how to get the content of input text in node js

I need to get the data entered in the input text. Using document.getElementById, but displays the error: ReferenceError: document is not defined.
That is, I need to click on the button i get all the data that the user entered.
.........................................................................
.........................................................................
.........................................................................
.........................................................................
.........................................................................
.........................................................................
const express = require('express');
const router = express.Router();
const Cookies = require('cookies');
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// console.log(res.headers(['cookie']));
// res.setHeader('Set-Cookie', 'TestHeader=HeaderValue');
const cookies = new Cookies(req, res);
if (req.url === '/favicon.ico') {
res.end();
return;
}
cookies.set('admin', 'true');
console.log(cookies.get('node'));
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="signUp.js" defer></script>
</head>
<body>
<h1>Sign Up Form</h1>
<form method="POST" action="/sign-up" autocomplete="off">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required autocomplete="off">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" required autocomplete="off">
</div>
<div>
<label for="password_confirmation">Password again</label>
<input type="password" name="password_confirmation" id="password_confirmation" required autocomplete="off">
</div>
<button id="sign_up_btn">Sign Up</button>
</form>
Sign In
</body>
</html>
`);
const userName = document.getElementById('name');
const userEmail = document.getElementById('email');
const userPassword = document.getElementById('password');
const userData = [userName, userEmail, userPassword];
for (let i = 0; i < userData.length; i += 1) {
console.log(userData[i]);
}
});
router.post('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.statusCode = 501;
res.end('Not implemented yet!...');
});
module.exports = router;
please place the script before </body>, or in window.onload callback function. Because document object is not created when you call document.getElementById
You've edited your question so allow me to edit my answer:
Your implementation here is incorrect. You are using Express to serve a webpage with a form. In order to evaluate the values of the form, you'll need to decide if you want to do that on the client side or the server side.
Your form looks like a login form, so you'll want to process this on the server side.
const express = require('express');
const router = express.Router();
const Cookies = require('cookies');
const bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded());
router.use(bodyParser.urlencoded({ extended: true }));
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// console.log(res.headers(['cookie']));
// res.setHeader('Set-Cookie', 'TestHeader=HeaderValue');
const cookies = new Cookies(req, res);
if (req.url === '/favicon.ico') {
res.end();
return;
}
cookies.set('admin', 'true');
console.log(cookies.get('node'));
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="signUp.js" defer></script>
</head>
<body>
<h1>Sign Up Form</h1>
<form method="POST" action="/sign-up" autocomplete="off">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" required autocomplete="off">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" required autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" required autocomplete="off">
</div>
<div>
<label for="password_confirmation">Password again</label>
<input type="password" name="password_confirmation" id="password_confirmation" required autocomplete="off">
</div>
<button id="sign_up_btn">Sign Up</button>
</form>
Sign In
</body>
</html>
`);
router.post('/sign-up', (req, res) => {
const { name, email, password } = req.body;
// do stuff with name, email, password
});
});
router.post('/', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.statusCode = 501;
res.end('Not implemented yet!...');
});
module.exports = router;
For client side form processing, you could do something like this:
HTML
<form action="#" onsubmit="handleSubmit(this)">
<input type="text" name="foo" value="bar" />
<input type="submit" value="Submit" />
</form>
Javascript
function handleSubmit(e) {
console.log(e.foo.value)
}
Example

Firebase cannot signup users with email and password

I am using firebase to signup users using email and password on my website. I have enabled email and password signup on my console. When I signup an user on the web page, the user email and password do not get passed to Firebase, and no error is displayed neither.
Her is my front end code
<!DOCTYPE html>
<html>
<head>
<title>Registration </title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-database.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="signup.js" defer></script>
</head>
<body>
<form id="form">
<div class="header">
<h2>Sign up as a Language Learner</h2>
</div>
<div class="input">
<input id="username" type="text" name="username" placeholder="Username">
</div>
<div class="input">
<input id="email" type="email" name="email" placeholder="Email">
</div>
<div class="input">
<input id="password1" type="password" name="password_1" placeholder="Password">
</div>
<div class="input">
<input id="password2" type="password" name="password_2" placeholder="Confirm Password">
</div>
<div>
<p id="message">
</p>
</div>
<div class="input">
<button id="register_button" class="btn" name="signup">Register</button>
<p class="input">Already a member? Sign in
&nbsp Cancel
</p>
</div>
</form>
<div id="signup_success">
<h2>Sign-up Successful!</h2>
</div>
</body>
</html>
Here is my signup.js file:
var password2 = document.querySelector("#password2").value;
var register_button = document.querySelector("#register_button");
var config = {
apiKey: "111",
authDomain: "222",
databaseURL: "333",
projectId: "444",
storageBucket: "555",
messagingSenderId: "666"
};
firebase.initializeApp(config);
register_button.onclick = function() {
var email = document.querySelector("#email").value;
var password1 = document.querySelector("#password1").value;
firebase.auth().createUserWithEmailAndPassword(email, password1).catch(function(error) {
alert("hello");
var errorCode = error.code;
var errorMessage = error.message;
document.querySelector("#message").innerHTML = errorCode + ": " + errorMessage;
})
}
I have my config setup properly with the data from the console. If I get rid of register_button.onclick = function(), the firebase.auth().createUserWithEmailAndPassword executes. I tried to add register_button.addEventListener("click", register_user, false); at the end and it does not work either.
I have no idea what is wrong with this, any help and advice is very appreciated. Thanks in advance.
*Edit: Thanks to #Fire-in-D-Hole below, it was due to my tag in HTML, using tag messes up with what we submit on Firebase. Lesson learned: never use when using Firebase
Your code is absolutely Correct. However, There seems to be an Extra Space in the method createUserWithEmailAndPassword(email, password1) which is causing the issue.
Please change it to createUserWithEmailAndPassword(email,password1).
Also, When I click on Register it seems you are using Form Tagand the values are being displayed in the Address bar(See Below). Suggest you to Please check as you might not want to show Details in the Address bar.
Users Registered Screenshot:
Lastly, you are using Two fields as password make sure you have the logic Written that both the password fields have to be matched. Adding the Code below which I tried and it doesn't have Form tags.
var password2 = document.querySelector("#password2").value;
var register_button = document.querySelector("#register_button");
var config = {
apiKey: "111",
authDomain: "1111",
databaseURL: "1111",
projectId: "1111",
storageBucket: "11111",
messagingSenderId: "111"
};
firebase.initializeApp(config);
register_button.onclick = function() {
var email = document.querySelector("#email").value;
var password1 = document.querySelector("#password1").value;
var password2= document.querySelector("#password2").value;
//alert("heyman im in register button");
//console.log("Email" +email);
// console.log("password1 Value" +password1);
// console.log("password2 Value" +password2);
firebase.auth().createUserWithEmailAndPassword(email, password1).catch(function(error) {
//alert("hello");
var errorCode = error.code;
var errorMessage = error.message;
document.querySelector("#message").innerHTML = errorCode + ": " + errorMessage;
});
}
<!DOCTYPE html>
<html>
<head>
<title>Registration </title>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-database.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script src="signup.js" defer></script>
</head>
<body>
<div class="header">
<h2>Sign up as a Language Learner</h2>
</div>
<div class="input">
<input id="username" type="text" name="username" placeholder="Username">
</div>
<div class="input">
<input id="email" type="email" name="email" placeholder="Email">
</div>
<div class="input">
<input id="password1" type="password" name="password_1" placeholder="Password">
</div>
<div class="input">
<input id="password2" type="password" name="password_2" placeholder="Confirm Password">
</div>
<div>
<p id="message">
</p>
</div>
<div class="input">
<button id="register_button" class="btn" name="signup">Register</button>
<p class="input">Already a member? Sign in
&nbsp Cancel
</p>
</div>
<div id="signup_success">
<h2>Sign-up Successful!</h2>
</div>
</body>
</html>
You need to use the .onAuthStateChanged observer to handle the signin state change.

crypto.js:562 return binding.PBKDF2(password, salt, iterations, keylen, digest, callback);

I am getting the following error :
crypto.js:562
return binding.PBKDF2(password, salt, iterations, keylen, digest, callback);
^
TypeError: Not a buffer
at TypeError (native)
at pbkdf2 (crypto.js:562:20)
at Object.exports.pbkdf2 (crypto.js:548:10)
at pbkdf2 (/home/ubuntu/workspace/GroupWrites/node_modules/passport-local-mongoose/index.js:56:14)
at InternalFieldObject.ondone (/home/ubuntu/workspace/GroupWrites/node_modules/passport-local-mongoose/index.js:105:9)
[nodemon] app crashed - waiting for file changes before starting...
It was working fine before I implemented a confirm password feature. My form looks like this:
<div class="row">
<h1 style="text-align: center">Create Your Account</h1>
<div style="width: 20%; margin: 25px auto;">
<form action="/register" method="post">
<div class="form-group">
<label>Username</label>
<input class="form-control" type="text" name="username" placeholder="hermioneGranger">
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="text" name="email" placeholder="hermioneGranger#hogwarts.edu">
</div>
<div class="form-group">
<label>Password</label>
<input id="password" class="form-control" type="password" name="password" placeholder="gryffindor3" autocomplete="new-password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input id="confirm_password" class="form-control" type="password" name="password" placeholder="gryffindor3" autocomplete="new-password">
</div>
<div class="form-group" style="text-align: center">
<button id="button" class="btn btn-lg">Create</button>
</div>
</form>
</div>
</div>
<!--Confirm Password Script-->
<script type="text/javascript">
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
And my user schema looks like this :
var mongoose = require("mongoose")
var passportLocalMongoose = require("passport-local-mongoose")
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
subscriptions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Story"
}
]
})
UserSchema.plugin(passportLocalMongoose)
module.exports = mongoose.model("User", UserSchema)
Please help. Cannot figure this one out. I found out about something called bcrypt and tried to require it in my app.js and get something working but that would not solve my issues. I believe it has something to do with the confirm password script, because before I added it I was making accounts just fine.

Categories