Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
When a new image is added, the old image is automatically replasing in nodejs how to fix

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




   

`

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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 imagePath = './public/product-images/' + imageName;
console.log(imagePath);
image.mv(imagePath, (error) => {
    //something here
})

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda