添加新图像时,节点js中的旧图像会自动替换如何修复

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

我已经创建了一个可以成功上传图像的文件,但是在这个项目中出现的图像名称 (undefiend.jpg) 使用了 express 文件上传中间件

*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;

产品-helpers.js
在这里我使用 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)
    })
  
  
     }
   
}
 




   

`

我认为你应该使用 data.insertedId,

  module.exports = {
    addProduct: (product, callback) => {
        db.get().collection('product').insertOne(product).then((data) => {
            callback(data.insertedId)
        })
    }
}

在 mongodb 文档 https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/ 中,显示 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")
}

但无论如何,您可以使用 req.files.image 中的名称 属性:例如:

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

如果您想使用更多属性,请看这里: https://www.npmjs.com/package/express-fileupload