I am trying to upload a form data consisting of name, email, and pdf file and i am currently stuck at uploading part when I submit the form I get this error:
html part (form):
<form action="/homeupload" method="post" id="homup1" [enter image description here](https://i.stack.imgur.com/nJIQL.png)enctype="multipart/form-data">
<div >
<label for="employeename" >Name</label>
<input
type="text"
id="employeename"
name="homename"
/>
</div>
<div >
<label for="homeemail" >Email address</label>
<input
type="email"
id="homeemail"
name="homeemail"
/>
</div>
<div >
<label for="homepassword" >Password</label>
<input
type="password"
id="homepassword"
name="homepassword"
/>
</div>
<div >
<label for="homefile" >File</label>
<input
type="file"
id="file"
name="file"
accept=".pdf"
/>
</div>
<button type="submit" >Submit</button>
</form>
userupload schema part :
const mongoose = require("mongoose");
const uploadSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password_: {
type: String,
},
date: {
type: Date,
required: true,
default: Date.now,
},
file: {
type: String,
required: true,
},
});
const Upload = mongoose.model("Uploaddb", uploadSchema);
module.exports = Upload;
app.js part:
//packages required
require("dotenv").config();
const express = require("express");
const path = require("path");
const res = require("express/lib/response");
const app = express();
const hbs = require("hbs");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
require("./db/conn");
require("./models/userUpload");
const Register = require("./models/register");
const port = process.env.PORT;
const Uploaddb = require("./models/userUpload");
//upload part
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const Grid = require("gridfs-stream");
const methodOverride = require("method-override");
// const conn = require("./db/conn");
// seting path (other imports)---------------------------
const static_path = path.join(__dirname, "../Public");
const views_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
//middleware sort of access points--------
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(static_path));
app.set("view engine", "hbs");
app.set("views", views_path);
hbs.registerPartials(partials_path);
//upload middleware
app.use(bodyParser.json());
app.use(methodOverride("_method"));
//Init gfs
let gfs;
const mongoURI = "mongodb://127.0.0.1:27017/capprojmongod";
const conne = mongoose.createConnection(mongoURI);
conne.once("open", () => {
// Init stream
gfs = Grid(conne.db, mongoose.mongo);
gfs.collection("Uploads");
console.log("in once");
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
console.log(" storage engine ke andar startpe ");
return new Promise((resolve, reject) => {
console.log(" storage engine ke andar promise startpe ");
console.log("in upload");
const filename = file.originalname;
const fileInfo = {
filename: filename,
bucketName: "Uploads",
};
console.log(" storage engine ke andar resolve ke pehele pe");
resolve(fileInfo);
console.log("uploaded________________");
});
console.log("uploaded");
},
});
// initialize upload middleware
const uploading = multer({ storage });
// set up the form submission route
app.post("/homeupload", uploading.single("file"), async (req, res) => {
// res.json({ file: req.file });
try {
const hemail = req.body.homeemail;
const hpass = req.body.homepassword;
const ishuser = await Register.findOne({ email: hemail });
if (ishuser) {
// console.log(ishuser);
const ispmatch = await bcrypt.compare(hpass, ishuser.password);
if (ispmatch) {
// console.log("p true");
const newUpload = new Uploaddb({
name: req.body.homename,
email: req.body.homeemail,
file: req.body.file,
});
// save the form submission to the database
const userdatauploaded = await newUpload.save();
res.status(201).render("home");
} else {
res.send("Invalid password__");
}
} else {
res.send("Invalid email-id");
}
} catch (error) {
console.log(error);
res.send(error);
}
});
//route get/ i.e. rendering page #1 i.e. login page-------
app.get("/", (req, res) => {
res.render("login");
});
//route get /home page i.e. rendering page #2 i.e. home page-------
app.get("/home", (req, res) => {
res.render("home");
});
app.post("/login", (req, res) => {
res.render("login");
});
//creating new user in db (registering new user at page #1)-------
app.post("/register", async (req, res) => {
try {
const email = req.body.email;
const isUserEmail = await Register.findOne({ email });
if (isUserEmail) {
res.send("Email already registered. Kindly sign in to proceed");
} else {
const registerusers = new Register({
full_name: req.body.name,
email: req.body.email,
password: req.body.rpassword,
});
// console.log(req.body.name); //name
//storing cookie
const token = await registerusers.generateAuthToken();
// console.log("token in app.js during registeration is ", token);
res.cookie("jwt", token, {
expires: new Date(Date.now() 90000),
httpOnly: true,
});
// console.log("cookie generated during registration app.js ", jwcookie);
const registered = await registerusers.save();
res.status(201).render("home");
}
} catch (error) {
res.status(400).send(error);
}
});
//login check page #1 -------------------------
app.post("/signin", async (req, res) => {
try {
const siemail = req.body.siemail;
const sipass = req.body.sipassword;
const userinfo = await Register.findOne({ email: siemail });
if (userinfo) {
const ismatch = await bcrypt.compare(sipass, userinfo.password);
const token = await userinfo.generateAuthToken();
res.cookie("jwt", token, {
expires: new Date(Date.now() 90000),
httpOnly: true,
// secure:true,
});
if (ismatch) {
res.status(201).render("home");
} else {
res.send("Invalid credentials");
}
// console.log(userinfo);
// console.log(`${siemail} and password is ${sipass}`);
} else {
res.send("Not registerd ");
}
} catch (error) {
res.status(400).send("wrong email");
}
});
app.listen(port, () => {
console.log(`server is running on port number ${port}`);
console.log("hi i am abhinav");
});
the main error its showing is:
Error: Uploaddb validation failed: file: Path `file` is required.
at ValidationError.inspect (E:\cap pro\mern_backend - Copy - Copy\node_modules\mongoose\lib\error\validation.js:50:26)
at formatValue (node:internal/util/inspect:806:19)
at inspect (node:internal/util/inspect:365:10)
at formatWithOptionsInternal (node:internal/util/inspect:2273:40)
at formatWithOptions (node:internal/util/inspect:2135:10)
at console.value (node:internal/console/constructor:340:14)
at console.log (node:internal/console/constructor:377:61)
at E:\cap pro\mern_backend - Copy - Copy\src\app.js:118:13
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
errors: {
file: ValidatorError: Path `file` is required.
at validate (E:\cap pro\mern_backend - Copy - Copy\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaType.doValidate (E:\cap pro\mern_backend - Copy - Copy\node_modules\mongoose\lib\schematype.js:1330:7)
at E:\cap pro\mern_backend - Copy - Copy\node_modules\mongoose\lib\document.js:2903:18
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
properties: [Object],
kind: 'required',
path: 'file',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Uploaddb validation failed'
}
I am not able to understand that what file path its talking about, it's sound stupid but i even changed the name and id of file section. X--
CodePudding user response:
Instead of:
const newUpload = new Uploaddb({
name: req.body.homename,
email: req.body.homeemail,
file: req.body.file,
});
Try it:
const newUpload = new Uploaddb({
name: req.body.homename,
email: req.body.homeemail,
file: req.file.path,
});
CodePudding user response:
well I still did not understand what was triggering the error but i found the solution instead of file:req.file.file
or file:req.file.path
it should be file:req.file.filename
because what i need to transfer to my db is the file name (string) not file (.pdf)
const newUpload = new Uploaddb({
name: req.body.homename,
email: req.body.homeemail,
file: req.file.path,
});
credit to my anonymus friend XD