how to insert array of objects in mongodb using express js - javascript

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

Related

How to transfer image upload from form to backend upload?

I managed to upload an image in form, but i want to save it to backend and then when i call it again using frontend i will b able to save a picture
function code :
addFilm: (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost, rating, special_features, category_id, actors, store_id, callback) => { //1.(1 ~ 3 are places to change code )
var conn = db.getConnection(); // GET CONNECTION TO DB
conn.connect((err) => {
if (err) {
console.log(err);
return callback(err, null);
} else {
console.log('Connected Successfully!');
var SQLstatement = //use backtick to go onto next line
// first insert into film table
`insert into film (title,description,release_year,language_id,rental_duration,rental_rate,length,replacement_cost,rating,special_features)
Values(?,?,?,?,?,?,?,?,?,?)`; // 2.
conn.query(SQLstatement, [title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost, rating, special_features], (error, result_id) => { //3.
if (error) {
console.log(error);
return callback(error, null);
}
else {
// second insert into film_category table
var SQLstatement = `insert into film_category (film_id,category_id) Values (?,?)`
conn.query(SQLstatement, [result_id.insertId, category_id], (error, result) => {
if (error) {
console.log(error);
return callback(error, null);
}
else {
console.log(result);
// neeed check actor
console.log(actors);
var SQLstatement = ''
values = []
// add a new actor id with the same film id to the film_actor table
for (var k = 0; k < actors.length; k++) {
if (k == actors.length - 1) {
SQLstatement += `(?,?)`
}
else {
SQLstatement += `(?,?),`
}
// console.log(actors[k])
values.push(actors[k])
values.push(result_id.insertId)
}
var finalSQLstatement = `insert into film_actor (actor_id,film_id) Values ` + SQLstatement
conn.query(finalSQLstatement, values, (error, result) => {
if (error) {
console.log(error);
return callback(error, null);
}
})
console.log(result_id.insertId);
var SQLstatement = //use backtick to go onto next line
// last insert into inventory with same film_id and store_id
`insert into inventory(film_id,store_id) Values(?,?)`; // 2.
conn.query(SQLstatement, [result_id.insertId, store_id], (error, result) => { //3.
conn.end();
if (error) {
console.log(error);
return callback(error, null);
}
else {
console.log(result);
return callback(null, result.insertId);
}
});
}
})
// });
}
});
}
});
},
app.get():
app.get('/view/:filmid',function(req, res){
var filmid = req.params.filmid;
actorDB.getDetails(filmid, function(err, result){
if(!err){
console.log(result);
res.send(result);
}else{
res.status(500).send("Some error");
}
});
});
index.html:
<!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>Customer</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<nav class="nav">
<a class="nav-link" href="/">Home</a>
<a class="nav-link" href="/users/">All Users</a>
</nav>
<h1>Register a new DVD</h1>
<form id="register-form">
<div class="form-group">
<div class="file-upload w-100">
<form class="image-upload-wrap d-flex justify-content-center align-items-center"
style="height: 240px">
<input class="file-upload-input" type="file" onchange="readImage(this);" accept="image/*"
id="imageFile" />
<div class="drag-text w-100 d-flex flex-column justify-content-center align-items-center">
<div id="imageErr" class="text-danger d-none">
Invalid Image
</div>
<h3>Drag photo here</h3>
<p>— or —</p>
<button class="btn bg-secondary text-white font-weight-bold text-center" type="button"
style="white-space: nowrap; z-index: 1055" id="addImage"
onclick="$('.file-upload-input').trigger( 'click' )">
Choose photo to upload
</button>
</div>
</form>
<div class="file-upload-content">
<img class="file-upload-image" style="border: 1px black solid" src="#" alt="your image"
id="imgPreview" />
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
function readImage(fileInput) {
if (fileInput.files && fileInput.files[0]) {
var imgReader = new FileReader();
imgReader.onload = function (event) {
var wrap = document.querySelector(".image-upload-wrap");
if (wrap) {
wrap.classList.add("d-none");
wrap.classList.remove("d-flex");
}
var imgData = event.target.result.split(',')[1];
var postData = { image: imgData };
fetch('/upload-image.php', {
method: 'POST',
body: JSON.stringify(postData),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
document.getElementById("addImage").style.display = "none";
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = event.target.result;
var content = document.querySelector(".file-upload-content");
content.classList.add("d-flex", "justify-content-center", "align-items-center");
content.classList.remove("d-none");
var btnSave = document.getElementById("save");
if (btnSave.classList.contains("btn-danger")) {
btnSave.classList.toggle("btn-danger");
btnSave.classList.add("btn-primary");
btnSave.innerHTML = "Save as promo picture";
}
};
imgReader.readAsDataURL(fileInput.files[0]);
} else {
removeUpload();
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, requestBody, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(requestBody)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/login");
});
}
</script>
</body>
</html>
I need help in parsing the data, even now as i try to submit the form it says Cannot read properties of null (reading 'classList')
at imgReader.onload.

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>

Not submit data in mongodb database

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

In HTML, name="object[prop]" doesn't seem to work

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

Form submit displays javascript coe instead of executing it

I'm trying to create an HTML form that will send an email using the information inputed. For now however, I just hard coded the information into the script itself, so the field inputs don't matter. However, whenever I press the Submit button, is simply displays the Javascript to the screen instead of executing it. The script is in the same directory as the HTML.
I tested it by running it directly from the Ubuntu terminal and successfully received an email from it.
I'm running this on Ubuntu 16.04, Node v6.14.3. The HTMl uses Bootstrap 4, and the email process is with Nodemailer. Thank you very much for your time.
-Joel
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'redacted',
pass: 'redacted'
}
});
const mailOptions = {
from: 'redacted',
to: 'redacted',
subject: 'hey',
text : 'text',
html: '<p>Your html here</p>',
attachments:[
{
filename: 'anglerite.png',
path: '/home/joel/Desktop/Anglerite/img/anglerite.png'
}
]
};
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else
console.log(info);
});
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="css/bootstrap-social.css">
<link rel="stylesheet" href="css/styles.css">
<title>Redacted</title>
</head>
<form" class = "col-sm-6" action = "app4.js" method = "POST" >
<div class = "row form-row form-group">
<div class = "col-sm-5">
<input type = "text" class = "form-control-plaintext full-width" id = "name" placeholder = "Your name here">
</div>
<div class = "col-sm-2">
</div>
<div class = "col-sm-5 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "staticEmail" placeholder = "email#example.com">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "phone" placeholder = "Phone number with area code">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<input type = "text" class = "form-control-plaintext full-width" id = "subject" placeholder = "Subject">
</div>
</div>
<div class = "row form-row form-group">
<div class = "col-sm-12 widen-slightly">
<textarea rows = "6" class = "form-control-plaintext full-width" id = "Description" placeholder = "Description"></textarea>
</div>
</div>
<div class = "row form-row form-group">
<label class = "col-sm-3 col-form-label" >Any Photos</label>
<div class = "col-sm-7">
<input type = "file" class = "form-control-file full-width" id = "">
</div>
<div class = "cl-sm-2">
<button type="submit" class="btn btn-default" id = "submit">Submit</button>
</div>
</div>
</form>
EDIT: Chris Happy's answer proposed moving the Javascript from an external file referenced only by the action property, to references to a in the same page.
I suspect you are redirecting to your script file rather than running the code on submit.
In other words, your form looks something like this:
<form action"script-file.js" method="GET">
<input type="text" value="Some text">
<input type="submit" value="Save">
</form>
However, that will redirect to your script file and it will display on the browser as plain text.
Instead, display your form and code like this:
<form id="myForm" action="/" method="GET">
<input type="text" value="Some text">
<input type="submit" value="Save">
</form>
<!-- Use: <script src="myscripts.js"></script> or -->
<script>
const myForm = document.getElementById('myForm');
myForm.addEventListener("click", () => {
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'redacted',
pass: 'redacted'
}
});
const mailOptions = {
from: 'redacted',
to: 'redacted',
subject: 'hey',
text: 'text',
html: '<p>Your html here</p>',
attachments: [{
filename: 'anglerite.png',
path: '/home/joel/Desktop/Anglerite/img/anglerite.png'
}]
};
transporter.sendMail(mailOptions, function(err, info) {
if (err)
console.log(err)
else
console.log(info);
});
});
</script>

Categories