Home > Net >  When a new image is added, the old image is automatically replasing in nodejs how to fix
When a new image is added, the old image is automatically replasing in nodejs how to fix

Time:05-10

I have created a file from which I can successfully upload the image, But the name of the image that comes up ( undefiend.jpg ) in this project use express file upload middleware

*admin.js

var express = require("express");

const productHelpers = require("../helpers/product-helpers");

var router = express.Router();
var productHelper = require("../helpers/product-helpers");

/* GET users listing. */
  router.get("/", function (req, res, next) {
  productHelpers.getAllProducts().then((products) => {
    console.log(products);
    res.render("admin/view-products", { admin: true, products });
  });
});
router.get("/add-product", function (req, res) {
  res.render("admin/add-product");
});

router.post("/add-product", (req, res, next) => {
  productHelpers.addProduct(req.body, (id) => {
    let image = req.files.Image;

    console.log(id);
    image.mv("./public/product-images/"   id   ".jpg", (err) => {
      if (!err) {
        res.render("admin/add-product");
      } else {
        console.log(err);
      }
    });
  });
});

module.exports = router;

product-helpers.js
Here i do callback using id

   product-helpers.js` var db=require('../config/connection')
 var collection=require('../config/collections')
 module.exports={
     addProduct:(product,callback)=>{
     

    db.get().collection('product').insertOne(product).then((data)=>{
          
      
      callback(data._id)
    })
  
  
     }
   
}
 




   

`

CodePudding user response:

I think you should use data.insertedId,

   module.exports={
     addProduct:(product,callback)=>{
     

    db.get().collection('product').insertOne(product).then((data)=>{
          
      
      callback(data.insertedId)
    })
  
  
     }
   
}

in the mongodb documentation https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/, it is showed that insertOne() returns

{    "acknowledged" : true,    "insertedId" :
     ObjectId("56fc40f9d735c28df206d078") }

Insert a Document without Specifying an _id Field In the following example, the document passed to the insertOne() method does not contain the _id field:

try {    db.products.insertOne( { item: "card", qty: 15 } ); } catch
 (e) {    print (e); };

The operation returns the following document:

{    "acknowledged" : true,    "insertedId" :
     ObjectId("56fc40f9d735c28df206d078") }

But anyway, you can use the name property from req.files.image: for example:

const image =req.files.image;
const imageName = image.name;
const imgPath = './public/product-images/' imageName;
    console.log(imgPath);
    image.mv(imgPath, (error)=>{
})

If you want to use more properties, look at here: https://www.npmjs.com/package/express-fileupload

  • Related