Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda