I have this working for a different Schema (I can show this code if needed) but when I tried to recreate it for another, it won't update my DB. It's connected to a MongoDB database and this functionality works with another Schema but this one does not
I've hit a dead end and have no idea a this point... Any help would be appreciated!!
Here is the POST controller
console.log("post");
const userId = req.body.userId;
const updatedName = req.body.name;
const updatedPassword = req.body.password;
const updatedEmail = req.body.email;
const updatedSkype = req.body.skype;
const updatedDepartment = req.body.department;
const updatedJobtitle = req.body.jobtitle;
const updatedLinemanager = req.body.linemanager;
const updatedNinumber = req.body.ninumber;
// const updatedJoinDate = req.body.joindate;
// console.log(req.body);
User.findById(userId)
.then((user) => {
isadmin = user.isadmin;
name = updatedName;
password = updatedPassword;
email = updatedEmail;
skype = updatedSkype;
department = updatedDepartment;
jobtitle = updatedJobtitle;
linemanager = updatedLinemanager;
ninumber = updatedNinumber;
joindate = user.joindate;
return user.save();
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));
};
The User model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
isadmin: {
type: Boolean,
required: true,
},
name: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
skype: {
type: String,
required: true,
},
department: {
type: String,
required: true,
},
jobtitle: {
type: String,
required: true,
},
linemanager: {
type: String,
required: true,
},
ninumber: {
type: String,
required: true,
},
joindate: {
type: Date,
required: true,
},
});
module.exports = mongoose.model("User", userSchema);
The Routes
router.get("/add-user", adminController.getAddUser);
router.get("/edit-user/:userId", adminController.getEditUser);
router.get("/edit-user-list", adminController.getEditUserList);
//POST USER
router.post("/add-user", adminController.postAddUser);
router.post("/edit-user/edit-user", adminController.postEditUser);
router.post("/edit-user", adminController.postEditUser);
router.post("/destroy-user", adminController.postDeleteUser);
And the HTML/EJS file
<%- include('../includes/head.ejs') %>
<link rel="stylesheet" href="/css/admin.css" />
<link rel="stylesheet" href="/css/add-user.css" />
<body>
<img src="pozzani.png" alt="pozzani logo" class="pozzanilogo" />
<div class="mainbackground">
<div class="leftcolumn">
<%- include('../includes/signout.ejs') %>
<%- include('../includes/nav.ejs') %>
<%- include('../includes/useful.ejs') %>
</div>
<div class="admin-column">
<h2 class="importanttitle">EDIT USER</h2>
<div class="update-container">
<h3 class="admin-title">Welcome to the USER edit tool</h3>
<p class="admin-content">Please edit forms below to make change. <b>ALL EDITS ARE FINAL!</b></p>
<form class="user-form" action="edit-user" method="POST">
<div class="form-section">
<label for="isadmin">Is Admin?</label>
<select id="isadmin" name="isadmin">
<% if (!user.isadmin) { %>
<option value="false" selected>False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="true">True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } else { %>
<option value="true" selected>True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } %>
</select>
</div>
<div class="form-section">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<%= user.name %>" >
</div>
<div class="form-section">
<label for="password">Password</label>
<input type="text" name="password" id="password" value="<%= user.password %>">
</div>
<div class="form-section">
<label for="email">Email</label>
<input type="email" name="email" id="email" value="<%= user.email %>">
</div>
<div class="form-section">
<label for="skype">Skype</label>
<input type="text" name="skype" id="skype" value="<%= user.skype %>">
</div>
<div class="form-section">
<label for="department">Department</label>
<input type="text" name="department" id="department" value="<%= user.department %>">
</div>
<div class="form-section">
<label for="jobtitle">Job Title</label>
<input type="text" name="jobtitle" id="jobtitle" value="<%= user.jobtitle %>">
</div>
<div class="form-section">
<label for="linemanager">Line Manager</label>
<input type="text" name="linemanager" id="linemanager" value="<%= user.linemanager %>">
</div>
<div class="form-section">
<label for="ninumber">National Insurance Number</label>
<input type="text" name="ninumber" id="ninumber" value="<%= user.ninumber %>">
</div>
<!-- <div class="form-section">
<label for="joindate">Join Date</label>
<input type="date" name="joindate" id="joindate" value="<%= user.joindate %>">
</div> -->
<input type="hidden" value="<%= user._id %>" name="userId">
<button class="admin-btn" type="submit"><% userId = user._id %>Edit User</button>
</form>
</div>
</div>
</div>
</body>
</html>
Please use findByIdAndUpdate() function instead of findById() and save()
for example;
User.findByIdAndUpdate(userId, {
isadmin: user.isadmin,
name: updatedName,
...
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));
Related
Here is my code
<div class="input-box" id="form-box">
<form action="/" method="post" id="form" autocomplete="off" class="form-box" >
<h2>Paste Everything Here</h2>
<input type="text" name="all" id="all-input">
<h2>OR</h2>
<input type="text" name="time" id="time" placeholder="Time">
<input type="text" name="link" id="link" placeholder="https//zoom.link">
<input type="tel" minlength="10" maxlength="10" placeholder="Phone Number" name="phonenumber" id="phonenumber">
<input type="submit" value="Send Later" id="send-later" class="send" name="action" formtarget="_self">
<input type="submit" value="Send Now" id="send-now" class="send" name="action" formtarget="_blank">
</form>
</div>
<div id="list-container" class="input-box">
<ul>
<% if(sendList) { %>
<% console.log(sendList) %>
<% for(var i = 1; i < sendList.length; i++) { %>
<li class="ui segment">
<form action="/" method="post">
<input type="hidden" name="time" value= "<%= sendList[i].time %>">
<input type="hidden" name="phonenumber" value= "<%= sendList[i].phonenumber %>">
<input type="hidden" name="link" value= "<%= sendList[i].link %>">
<strong><%= sendList[i].phonenumber %></strong>
- <%= sendList[i].time %> <br>
<!-- <%= sendList[i].link %> -->
<input type="submit" value="Send" name="action" formtarget="_blank">
<button >Delete</button>
</form>
</li>
<% }; } %>
</ul>
</div>
This is Index.js file
var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({ extended: true })
const cookieParser = require("cookie-parser");
const sessions = require('express-session');
// creating 24 hours from milliseconds
const oneDay = 1000 * 60 * 60 * 24;
//session middleware
app.use(sessions({
secret: "thisismysecrctekeyfhrgfgrfrty84fwir767",
saveUninitialized: true,
cookie: { maxAge: oneDay },
resave: false
}));
app.post("/" , urlencodedParser , (req , res) => {
if(req.body.action === "Send Now"){
console.log("in send now" + req.body.phonenumber);
console.log(req.body);
res.redirect(waMe.createFromNumberWithMessage("+91"+ req.body.phonenumber,
"Greetings! from support team \n" + req.body.link +
" \n\nAbove is the link for your free session with our expert counsellor \n\nYour session is scheduled for today at " + req.body.time));
}
if(req.body.action === "Send Later"){
console.log(req.session.index)
console.log(req.body);
if(req.session.index > 0){
req.session.index++;
console.log("im heree")
}
else {
req.session.index = 1;
req.session.sendlist = [];
console.log("im always here");
}
req.session.sendlist[req.session.index] = {time: req.body.time , link: req.body.link , phonenumber: req.body.phonenumber}
console.log(req.session.sendlist);
res.render("main" , {sendList: req.session.sendlist});
}
if(req.body.action === "Send"){
console.log(req.body);
res.redirect(waMe.createFromNumberWithMessage("+91"+req.body.phonenumber,
"Greetings! from support team \n" + req.body.link +
" \n\nAbove is the link for your free session with our expert counsellor \n\nYour session is scheduled for today at " + req.body.time + "\n\n It is starting soon! Join now."));
}
});
Here is the output:
I'm new to JavaScript and can't figure this out. The send now button used to work when I didn't have other submit buttons added.
As you can see, the req.body is unpopulated when I click send now and populated when I click send Later or Send Button in the <ul> <li> list.
I am using EJS and Express for an application I am doing just for fun.
In my application, I am utilizing partials from a folder called views/partials. My css stylesheet is located in a directory called public. I have included app.use(express.static(path.join(__dirname, 'public'))); in my express routes directory. And it is working on all other pages besides this one, (edit.ejs):
<%- include('partials/head') %>
<div id="updatecustomer">
<h1>Update Customer Profile</h1>
<form method="post" action="/<%=customer.id%>?_method=PATCH">
<label for="firstname">First Name</label>
<input type="text" name="firstName" id="firstname" placeholder="<%= customer.firstName %>">
<label for="lastname">Last Name</label>
<input type="text" name="lastName" id="lastname" placeholder="<%= customer.lastName %>">
<label for="phonenumber">Phone Number</label>
<input type="text" name="contactNumber" id="phonenumber" placeholder="<%= customer.contactNumber %>">
<label for="address">Address</label>
<input type="text" name="address" id="address" placeholder="<%= customer.address %>">
<label for="city">City</label>
<input type="text" name="city" id="city" placeholder="<%= customer.city %>">
<label for="state">State</label>
<input type="text" name="state" id="state" placeholder="<%= customer.state %>">
<label for="zipcode">Zipcode</label>
<input type="text" name="zipcode" id="zipcode" placeholder="<%= customer.zipcode %>">
<button type="submit">Update Customer</button>
</form>
</div>
A snippet from index.js of my get/patch request, (I'm not using a database, simply an array of objects.):
app.get('/:id/edit', (req, res) => {
const { id } = req.params;
const customer = customers.find(c => c.id === id)
res.render('edit', { customer })
})
app.patch('/:id', (req, res) => {
const { id } = req.params;
const foundCustomer = customers.find(c => c.id === id);
const customerFirstname = req.body.firstName;
foundCustomer.firstName = customerFirstname;
const customerLastname = req.body.lastName;
foundCustomer.lastName = customerLastname;
const customerAddress = req.body.address;
foundCustomer.address = customerAddress;
const customerCity = req.body.city;
foundCustomer.city = customerCity;
const customerState = req.body.state;
foundCustomer.state = customerState;
const customerZip = req.body.zipcode;
foundCustomer.zip = customerZip;
const customerContactNum = req.body.contactNumber;
foundCustomer.contactNumber= customerContactNum;
res.redirect('/');
})
I have tried adding the styles manually to the page, clearing my browser data, and spent hours looking up a solution and remained stumped on this issue. Any ideas?
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
When I console.log the req.body it gives me:
[Object: null prototype] {
'shoe[name]': 'Shoe Name',
'shoe[description]': '',
'shoe[pictures]': '',
'shoe[collections]': 'Shoe Collection'
}
But when I console.log req.body.shoe It prints undefined,
been breaking my head for a few days now
The form:
<form action="/shoes/" method="post">
<input type="text" name="shoe[name]" placeholder="Name of the shoe">
<textarea name="shoe[description]" cols="30" rows="10"></textarea>
<input type="file" name="shoe[pictures]">
<input type="text" name="shoe[collections]">
<input type="submit" value="Post the Shoe">
</form>
Shoe Model:
const mongoose = require('mongoose');
const shoeSchema = new mongoose.Schema({
name: { type: String, unique: true },
description: String,
displayPicture: mongoose.Schema.Types.ObjectId,
pictures: [ { type: mongoose.Schema.Types.ObjectId } ],
collections: [ { type: mongoose.Schema.Types.ObjectId, unique: true } ],
dateOfPublish: { type: Date, default: Date.now },
comments: [
{
userId: { type: mongoose.Schema.Types.ObjectId, unique: true, ref: 'Comment' }
}
]
});
module.exports = mongoose.model('Shoe', shoeSchema);
Node.js + Express create route:
//Create
router.post('/', (req, res) => {
console.log(req.body.shoe);
Shoe.create(req.body.shoe, (err, shoe) => {
if (err) {
console.log(err);
} else {
return res.redirect('/');
}
});
});
You cannot implement the below way the html part
<input type="file" name="shoe[pictures]">
You yourself is seeing that
[Object: null prototype] {
'shoe[name]': 'Shoe Name',
'shoe[description]': '',
'shoe[pictures]': '',
'shoe[collections]': 'Shoe Collection'
}
'shoe[pictures]' is the entire key and you are only accessing req.body.shoe
First your entire HTML need to be changed.
<form action="/shoes/" method="post">
<input type="text" name="name" placeholder="Name of the shoe">
<textarea name="description" cols="30" rows="10"></textarea>
<input type="file" name="pictures">
<input type="text" name="collections">
<input type="submit" value="Post the Shoe">
</form>
And then in backend in req.body object you will receive all the properties name,description,pictures,collections
After that you can access
req.body.name
req.body.description etc
Then in backend you need to define
var shoe = {...req.body}
and then you can use shoe object
<% include ../partials/header %>
<div class="row">
<div class="col-md-4">
<h2><%= user.firstName + " " + user.lastName %></h2>
<div class="thumbnail">
<img src="<%= user.avatar %>" alt="user profile image">
<div class="caption"><%= user.email %></div>
</div>
</div>
<div class="col-md-8">
``` <h3><%= user.username %>'s campgrounds</h3>
<% campgrounds.forEach(campground => { %>
<div class="col-md-4 col-sm-6">
<div class="thumbnail card">
<img src="<%= campground.image.url %>" alt="<%= campground.name %>">
<div class="caption">
<h4 class="caption"><%= campground.name %></h4>
</div>
</div>
</div>
<% }); %>
</ul>
</div>
Edit Profile
</div>
<% include ../partials/footer %>
Can you see that %include is written here. if that statement is not present in your code it will not work. That is what i am trying to explain from that time
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Shoe</title>
</head>
<body>
<form action="/shoes/" method="post">
<input type="text" name="shoe[name]" placeholder="Name of the shoe">
<textarea name="shoe[description]" cols="30" rows="10"></textarea>
<input type="file" name="shoe[pictures]" value="Shoe Pictures">
<!-- tick the display pic -->
<input type="text" name="shoe[collections]">
<input type="submit" value="Post the Shoe">
</form>
</body>
</html>
In your there is nothing like that
The problem was with the body-parser, needed to use the qs library (true) instead of querystring(false) in the following line:
app.use(require('body-parser').urlencoded({ extended: true }));
originally extended was set to false.
for more info refer to this link
I am getting a bad request after I register a user. The data inserted into mongolab are fine, but it renders a page with "bad request". I checked my code like a hundred time and I can't find anything wrong with it.
Thank you
user model
var UserSchema = new Schema({
username: {type:String,
lowercase: true,
require: true
},
email: String,
isAdmin: String,
password: {type: String,
require: true
}
});
ejs
<form action="/user/register" method="POST">
<div class="form-group">
<label>Username: </label><input type="text" placeholder="username" name="username" class="form-control" />
</div>
<div class="form-group">
<label>Email:</label> <input type="email" placeholder="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label>Password:</label> <input type="password" placeholder="password" name="password1" class="form-control" />
</div>
<div class="form-group">
<label>Retype Password: </label><input type="password" placeholder="passowrd" name="password2" class="form-control" />
</div>
<button class="btn btn-success btn-lg">Register</button>
</form>
route
//register user
router.get("/register", function(req, res){
res.render("user/register");
});
router.post("/register", function(req, res){
if(req.body.password1!=req.body.password2){
return res.render("user/register");
}
var newUser = new User({
username: req.body.username,
email: req.body.email,
isAdmin: "false"
//password: req.body.password1
});
User.register(newUser, req.body.password1, function(err, user){
if(err){
//console.log(err + "skljflkjslflksddjfklsjdfkljsdlkjflksdjfkjsdklfjjfs;lk");
return res.render("user/register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/cues");
});
});
});