'issue with uploading and retriving images to mongoDB using express
I am building a beginner fullstack project where I am making a webstore. On here I have an admin route where I can upload new products to my mongoDB database so they get displayed on the store. Like any good webstore, I need images to show off my product, but I am having a hard time writing the code for that feature. I know there is something called GridFS, however my images will never exceed 16 MB so I dont want to overcomplicate my solution.
See the comments below the arrow in my code for the specific problem I am having
Schema for my products:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
productName: {type: String, required: true, unique: true},
image: {data: Buffer, contentType: String},
price: {type: Number, required: true}
}, {timestamps: true});
module.exports = mongoose.model("Product", UserSchema);
Add new product route:
const router = require("express").Router(); //
const Product = require("../models/Product"); //
//
router.post("/add", async (req, res) => { // // //
const newProduct = new Product({ // / //
productName: req.body.productName, //
image: { // this is where I have no idea what I am doing
data: req.body.image, // req.body.image is just the filename, do I need the entire path?
contentType: 'image/png' // not all images are png, how do I update this depending on image type?
},
price: req.body.price
});
try {
const savedProduct = await newProduct.save();
res.redirect("../products");
} catch (err) {
console.log(err);
console.log("an error occured when adding product");
res.redirect(400, "../products");
}
});
Display products page:
<% products.forEach(product => { %>
<article>
<h2><%= product.productName %></h2>
<div class="price"><%= product.price %></div>
<img src="<%= product.image %>" alt="">
</article>
<% }) %>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
