mongoose 错误:Uploaddb验证失败:file:需要路径'file

2w2cym1i  于 2023-01-05  发布在  Go
关注(0)|答案(2)|浏览(131)

我正在尝试上传一个由名称、电子邮件和PDF文件组成的表单数据,但我目前在提交表单时被卡在上传部分,我收到此错误:

html部分(表单):

<form class="homeform" action="/homeupload" method="post" class="homup" id="homup1" [enter image description here](https://i.stack.imgur.com/nJIQL.png)enctype="multipart/form-data">
            <div class="mb-3">
              <label for="employeename" class="form-label">Name</label>
              <input
                type="text"
                class="form-control"
                id="employeename"
                name="homename"
              />
            </div>
            <div class="mb-3">
              <label for="homeemail" class="form-label">Email address</label>
              <input
                type="email"
                class="form-control"
                id="homeemail"
                name="homeemail"
              />
            </div>
            <div class="mb-3">
              <label for="homepassword" class="form-label">Password</label>
              <input
                type="password"
                class="form-control"
                id="homepassword"
                name="homepassword"
              />
            </div>
            <div class="mb-3">
              <label for="homefile" class="form-label">File</label>
              <input
                type="file"
                class="form-control"
                id="file"
                name="file"
                accept=".pdf"
              />
            </div>
            <button type="submit" class="btn btn-light homebtn">Submit</button>
          </form>

用户上载架构部分:

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;

应用程序js部件:

//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");
});

其主要表现为:

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'
}

我不能够理解它所谈论的文件路径,这听起来很愚蠢,但我甚至改变了文件节的名称和ID。

yxyvkwin

yxyvkwin1#

取代:

const newUpload = new Uploaddb({
  name: req.body.homename,
  email: req.body.homeemail,
  file: req.body.file,
});

试试看:

const newUpload = new Uploaddb({
  name: req.body.homename,
  email: req.body.homeemail,
  file: req.file.path,
});
3phpmpom

3phpmpom2#

嗯,我仍然不明白是什么触发了错误,但我找到了解决方案,而不是file:req.file.filefile:req.file.path,它应该是file:req.file.filename,因为我需要传输到我的数据库是文件名(字符串),而不是文件(.pdf)

const newUpload = new Uploaddb({
  name: req.body.homename,
  email: req.body.homeemail,
  file: req.file.path,
});

归功于我的匿名朋友XD

相关问题