Learn how to quickly resolve the issue in nodejs where the new image automatically replaces the old one when added

I have successfully created a file to upload images, however the image name appears as undefined.jpg in this project. I am using the 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 is where 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)})
  
  
     }
   
}
 




   

`

Answer №1

Consider utilizing data.insertedId for optimal results,

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

The MongoDB documentation https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/ demonstrates that insertOne() provides

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

To Insert a Document without Specifying an _id Field, see the following example of using the insertOne() method without including the _id field:

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

The result of this operation will be:

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

Additionally, you can utilize the name attribute from req.files.image: for instance:

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

If more properties are needed, visit: https://www.npmjs.com/package/express-fileupload

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using relative URLs in HTML to navigate a specific group of requests via nodejs middleware

Alright, so let me dive into the details of my current dilemma. Essentially, I have a project implemented in node that serves a specific purpose. It's a website utilizing express, jade, and stylus. I have configured the routing for static content in ...

BlockUI - Uncaught error: The object does not contain the method 'blockUI'

Trying to implement the blockUI jQuery Plugin, I have added the necessary libraries in this way; <script src="http://malsup.com/jquery/block/jquery.blockUI.1.33.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

How to access JavaScript files from "bower_components" instead of "node_modules" using webpack

With the utilization of main-bower-files in my Gulp compilation tasks, it is not feasible for me to use webpack to require modules from the node_modules directory as it would interfere with the processing of CSS, images, and fonts in my current asset sys ...

Encountered Vue-Router issue: "SyntaxError: Unexpected token" while building module

I encountered an error while trying to compile this VueJS demo project. Despite updating NPM and the app's dependencies to the latest stable versions, the error persists. The error disappears when I remove vue-router from both index.js and main.js. T ...

React frontend communicating without backend server

Is it possible to send a message between two frontend users on web applications built with React? ...

Screen readers do not recognize the disabled attribute

I am currently using a stepper with a Material UI number field that is disabled. Despite the disablement, the screen reader is still able to adjust the number by incrementing and decrementing it. The corresponding HTML code is shown below: <input ari ...

Is there a way to modify the color scheme of the hamburger icon

I'm experiencing difficulties changing the color of a hamburger icon. I've searched for the specific code responsible for the color change, but I haven't been able to locate it. Ideally, I want the color to be white, but on small screens, i ...

The use of dates (YYYY-MM-DD) as identifiers in HTML/Angular 2 is causing issues

I have successfully created a calendar using html in Angular 2, and now I am looking to incorporate events into it. These events should be able to color specific days, add a dot inside the cell, or something similar. I have a json file that contains the ev ...

Leveraging the wheelDelta property in the onmousewheel event handler with Script#

When working with Script#, I often utilize mouse events using the ElementEvent argument. However, one thing seems to be missing - the WheelDelta property for handling the onmousewheel event. Can anyone provide guidance on how to access this property in t ...

AngularJS unit testing with $httpBackend is impacted by conflicts with UI-Router

Here is a controller that utilizes a submit function: $scope.submit = function(){ $http.post('/api/project', $scope.project) .success(function(data, status){ $modalInstance.dismiss(true); }) .error(function(data){ ...

Issue identified during the installation of npx create-react-app

click here to view the image I am puzzled as to why these errors are popping up when I just enter the command create-react-app. Can someone please help me resolve this issue? I am eager to get started on my project as quickly as possible. ...

Retrieve all the Firebase keys within a Vue script using Vue-Firebase

Trying to understand Firebase's handling of entries, I've been attempting to retrieve all keys from a child node. <div v-for="item in TeamArray"> {{item['.key']}} </div> Retrieving the keys from the HTML section works ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

Turn the camera to focus on the chosen object using three.js

I've been working on designing a map and I'm trying to achieve a specific functionality. When I select any geometry, I want the object to be positioned at the center of the viewport with the camera looking directly at it. Despite searching extens ...

I am looking to switch themes on the homepage using a button from an imported component

I have successfully created a toggle button on my main page in app.js to switch between dark and light themes. However, I am facing difficulty in putting the button inside my nav component and using it from that page imported in app.js. Can anyone guide me ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

Embarking on the Mongoose Journey

Every time I enter the code const mongoose = require("mongoose") An error message is displayed: /Users/user/shares3/node_modules/mongodb/lib/utils.js:1069 catch { ^ SyntaxError: Unexpected token { at createScript (vm. ...

Developing a custom model in nodejs without using an ORM or ODM

It's surprising how difficult this task has been to accomplish. I'm in the process of transforming my monolithic application into a 3-layer architecture for my Node.js Express app that uses a proprietary SQL database. Repository BEFORE archite ...

Arrange the colors in a predetermined sequence within the array

I am looking to implement a loop through an array and assign specific colors to each array element based on a predetermined order. Elements at positions first, fifth, ninth, and so on should be colored in red. Elements at positions second, sixth, tenth, a ...