Home > Software engineering >  how i can post to database contain these object a video and file and pdf with multer?
how i can post to database contain these object a video and file and pdf with multer?

Time:12-17

i have this database

const mongoose = require("mongoose");
const FormCourse_schema = new mongoose.Schema({
  FormCourse: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "cards",
    required: true,
  },
  date: { type: String },
  file: { type: String },
  video: { type: String },
  pdf: { type: String },
});
module.exports = mongoose.model("FormCourse", FormCourse_schema);

and this for posting for controller

exports.post_FormCourse = async (req, res, next) => {
  try {
    // if (!req.userId) return res.status(406).json({ massege: "Unauthenticated" });

    const FormCourse_id = req.body.FormCourse_id;
    const isFormCourse = FormCourse.findById(FormCourse_id);
    if (isFormCourse.lenght < 1) res.status(202).json("FormCourse not found");
    const course = new FormCourse({
      date: req.body.date,
      file: req.file.path,
      video: req.file.path,
      pdf: req.file.path,
    });
    const result = await course.save();
    res.status(200).send({
      result: result,
      request: {
        type: "GET",
        url: "localhost:3002/form/"   result._id,
      },
    });
  } catch (error) {
    res.status(404).json({ message: "invalid id", error: err });
  }
};

and this is the router what i define the post and here i suggest that the error show here

const express = require("express");
const router = express.Router();
const FormCourses = require("../controllers/formCourses");
const checkAuth = require("../middleware/checkAuth");
const multer = require("multer");

const storageautre = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads/filesautre");
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString().replace(/:/g, "-")   file.originalname);
  },
});
const fileFilterautre = (req, file, cb) => {
  // reject a file
  if (file.mimetype === "application/*") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};
const uploadautre = multer({
  storage: storageautre,
  fileFilter: fileFilterautre,
});

////////
const storagevideo = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads/filesvideo");
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString().replace(/:/g, "-")   file.originalname);
  },
});
const fileFiltervideo = (req, file, cb) => {
  // reject a file
  if (file.mimetype === "application/video") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};
const uploadvideo = multer({
  storage: storagevideo,
  fileFilter: fileFiltervideo,
});
// \\\\\\\\
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads/files");
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString().replace(/:/g, "-")   file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === "application/pdf") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
});
/*-----------------------------get all orders-----------------------------*/
router.get("/", FormCourses.get_FormCourse);
/*-----------------------------post order -----------------------------*/
router.post(
  "/",
  uploadautre.single("file"),
  uploadvideo.single("video"),
  upload.single("pdf"),
  FormCourses.post_FormCourse
);
/*-----------------------------update order-----------------------------*/
router.patch("/:courseId", checkAuth, FormCourses.patch_FormCourse);
/*----------------------------delete order-----------------------------*/
router.delete("/:delete", checkAuth, FormCourses.delete_FormCourse);
module.exports = router;

and lastly this app folder

const express = require("express");
const app = express();
const morgan = require("morgan");
// const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");

require("dotenv").config();

//-----------------------------add routers paths-----------------------------//

const cardsRouter = require("./src/router/Cards");
const formRouter = require("./src/router/FormCourses");
const histoRouter = require("./src/router/Historiques");
const secondCardsRouter = require("./src/router/SecondCards");
const usersRouter = require("./src/router/Users");
//-----------------------------Connect with mongodb-----------------------------//

mongoose
  .connect(process.env.DB_CONNECT)
  .then(() => console.log("mongo connected"))
  .catch((err) => console.log(err));

//-----------------------------middleware-----------------------------//
app.use(morgan("dev"));
app.use("/uploads", express.static("uploads"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    return res.status(200).json({});
  }
  next();
});
// app.use(express.static(path.join(__dirname, "public")));

//-----------------------------Routers---------------------------//

app.use("/users", usersRouter);
app.use("/card", cardsRouter);
app.use("/form", formRouter);
app.use("/histoRouter", histoRouter);
app.use("/secondCardsRouter", secondCardsRouter);

//-----------------------------Handling errors---------------------//

app.use((req, res, next) => {
  const error = new Error("Not found");
  res.status(404);
  next(error);
});
app.use((error, req, res, next) => {
  res.status(500 | Error.status).json({
    message: error.message,
  });
});
module.exports = app;

this show for 500 error testing with postman i think because of multiple fields of upload in router.post it throw to error so how it could be ?

CodePudding user response:

I couldn't fully understand your project, so I was not able to put the code in it.

But i think this can help you, it's a form that sends 3 files to mongo GridFS, you will get the data of the uploaded files, id and extension for example. To download the file it's just pass the id for the /download.

for example: http://localhost:3008/download?id=639bd2fe44f218a5e0ea58d4

const express = require('express')
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
const { GridFsStorage } = require('multer-gridfs-storage');
const multer = require('multer'); //use version 1.4.2

const connection = mongoose.connect("mongodb srv://ghazali:[email protected]/?retryWrites=true&w=majority");

const storage = new GridFsStorage({ db: connection });

const upload = multer({ storage });

let bucket;

connection.then(() => {
    bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db);
})

const app = express()

app.post('/upload', upload.array('files'), async (req, res) => {

    res.send(req.files); //req.files gives you the id and the extension, you can save to download the file later
})

app.get('/', async (req, res) => {

    res.send(`
    <form action="upload" method="post" enctype="multipart/form-data">
        <label for="pdf_file">PDF: </label>
        <input id="pdf_file" type="file" accept="application/pdf" name="files">
        <br>
        <br>
        
        <label for="pdf_file">File: </label>
        <input id="pdf_file" type="file" name="files">
        <br>
        <br>
        
        <label for="pdf_file">Video: </label>
        <input id="pdf_file" type="file" accept="video/*" name="files">
        <br>
        <br>
        <input type="submit">
    </form>
  `);
});

app.get("/download", (req, res) => {
    res.attachment("download"); //here you use the extension saved
    bucket.openDownloadStream(mongoose.Types.ObjectId(req.query.id)).pipe(res); //i am passing the id in the querystring, but you can pass other way
})


app.listen(3008, () => {
    console.log("Listening to 3008");
})
  • Related