i am try to store the product data in database but except images everthing is storing in database but images are coming to my local folder for ref please find the below code.
How can i solve this issue ?
images are storing in my local folder but not stoting in the database.
productSchema.js
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema(
{
name: { type: String, required: true, trim: true },
slug: { type: String, required: true, unique: true },
price: { type: Number, required: true },
description: { type: String, required: true, trim: true },
quantity: { type: Number, required: true },
offer: { type: Number },
productPictures: [{ img: { type: String } }],
reviews: [
{
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
review: String,
},
],
category: { type: mongoose.Schema.Types.ObjectId, ref: "Category" },
createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
updatedAt: Date,
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", productSchema);
productRoute.js
const router = require("express").Router();
const { requireSignin, adminMiddleware } = require("../common-middleware");
const { addProduct } = require("../controller/product");
const multer = require("multer");
const shortid = require("shortid");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(path.dirname(__dirname), "uploads"));
},
filename: function (req, file, cb) {
cb(null, shortid.generate() + "-" + file.originalname);
},
});
const upload = multer({ storage });
router.post(
"/create",
requireSignin,
adminMiddleware,
upload.array("productPicture"),
addProduct
);
router.get("/getallproducts");
module.exports = router;
productController.js
const Product = require("../models/product");
const slugify = require("slugify");
const shortid = require("shortid");
exports.addProduct = async (req, res) => {
// res.status(200).json({ file: req.files, body: req.body });
const { name, price, description, category, createdBy, quantity } = req.body;
let productPictures = [];
if (req.files.lenght > 0) {
productPictures = req.files.map((file) => {
return { img: file.filename };
});
}
const product = new Product({
name: name,
slug: slugify(name),
price,
quantity,
description,
productPictures,
category,
createdBy: req.user._id,
});
await product.save((error, product) => {
if (error) return res.status(400).json({ error });
if (product) {
res.status(201).json({ product });
}
});
};
For ref please find the attached images also