When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var user = require('./../model/user');
var path = require('path');
var upload = multer();
var awsUpload = require('./../config/fileUpload.js');
var Promise = require('promise');
var item = require('./../model/items.js');
var item_image = '';

var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './public/images')
    },
    filename: function(req, file, callback) {
        item_image = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
        callback(null, item_image)
    }
});


var addItem = function(req, res) {
    upload = multer({
        limits: {
            fileSize: 1000000,
            files: 1
        },
        storage: storage,
        fileFilter: function(req, file, callback) {
            var ext = path.extname(file.originalname)
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                return callback(res.end('Only images are allowed'), null)
            }
            callback(null, true);
        }
    }).single('item_img');
    upload(req, res, function(err) {
        var foodtruck_id = req.body.foodtruck_id;
        var newItem = new item();
        var itemList = [];
        newItem.item_name = req.body.item_name;
        newItem.item_tag = req.body.item_tag;
        newItem.item_description = req.body.item_description;
        newItem.item_category = req.body.item_category;
        newItem.item_discount_price = req.body.item_discount_price;

        for (var key in req.body) {
            if (req.body.hasOwnProperty(key)) {
                if (key == 'item_illustrations') {
                    newItem.item_illustrations = req.body[key];
                }
            }
        }
        newItem.item_stock = req.body.item_status;
        newItem.item_price = req.body.item_price;

        if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
            foodtruck.findById(foodtruck_id.trim(), function(err, foodtrucks) {
                if (err)
                    res.json({
                        status: '500',
                        message: 'There is no data available'
                    });

                newItem.save(function(err, savedItem) {
                    if (!err) {
                        foodtrucks.item_list.push(savedItem._id);
                        foodtrucks.save(function(err, truck) {
                            foodtruck.find({
                                _id: truck._id
                            }).populate('item_list').exec(function(err, foodtrucks) {
                                res.json({
                                    status: '200',
                                    message: 'New item added successfully',
                                    data: foodtrucks
                                });
                            });
                        });
                    } else {
                        res.json({
                            status: '500',
                            message: 'Error while saving new item'
                        });
                    }
                });


            });

        }
    });

};

In my app.js, I have the following route setup:

app.post('/test',addItem);

The issue arises when using req.body.hasOwnProperty with x-www-formurlencoded vs multipart-data through multer. The former works well but the latter gives me an error stating that req.body.hasOwnProperty is not a function. Is there any workaround to address this problem?

Answer №1

req.body is a unique object without any prototypes: it was generated using Object.create(null), so it doesn't inherit hasOwnProperty from Object.prototype. This design choice is advantageous because if a user included a field named hasOwnProperty, it could potentially disrupt the functionality of your code.

It's recommended to utilize the in operator instead:

if (key in req.body) {

However, for the loop scenario, there's no need for a check at all:

for (var key in req.body) {
    if (key == 'item_illustrations') {
        newItem.item_illustrations = req.body[key];
    }
}

In this specific instance, you can directly retrieve the desired value without iterating through a loop:

newItem.item_illustrations = req.body.item_illustrations;

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

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Is there a way to instruct npm to compile a module during installation using the dependencies of the parent project?

I am curious about how npm modules are built during installation. Let me give you an example: When I check the material-ui npm module sources on GitHub, I see the source files but no built files. However, when I look at my project's node_modules/mate ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. Additionally, I have a list of events structured as shown: id: "9", eventId: "1", title: "Training Network", st ...

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

Occasionally, the Twilio SMS and Whatsapp functionality fails to trigger within a serverless function when utilizing the Next.js API route on Vercel's production

In the following code snippet, you can see the implementation of the NextJS API route that is currently functional in a local environment. export default async function handler(request, response) { const accountSid = process.env.TWILIO_ACCOUNT_SID; con ...

Retrieving information from various datasets through inquiry

First Model const mongoose = require("mongoose"); const finalApprovalSchema = mongoose.Schema({ formId: String, designApproval: String, rejectionReason: String, date: { type: Date, default: Date.now, }, }); const FinalApproval ...

How do I import NPM modules in Angular 5 without using @types?

Currently experimenting with Angular 5 and beginning a project from angular-cli. I am interested in incorporating a NPM module called J2M (https://github.com/kylefarris/J2M). During my research, I came across these two commands: npm install j2m --save npm ...

A guide on integrating a submission button that combines values from multiple dropdown forms and redirects to a specific URL

Is there a way to make the submit button on this form act based on the combined values of two different dropdown menus? For instance, if "west" is selected from the first dropdown and "winter" is selected from the second dropdown, I want it to navigate to ...

Retrieving information from MongoDB within a Vue application using the MEVN stack

I am currently working on developing a full-stack Web Application and I have encountered some frustrating errors while fetching data in the .vue File. My code for fetching data looks like this: <script> import { createHydrationRenderer } from 'v ...

Is it possible to execute a function once another function has been called within a specific interval

Currently, I am working on a Greasemonkey script and have encountered an issue. The website contains a function that runs at regular intervals: jQuery(function1.run); setInterval(function1.run, function1.interval); I aim to execute my function immediatel ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

Implementing JWT authentication with express-restify-mongoose in MEAN Stack for selected REST methods

As a newcomer to this world, I appreciate your patience with me. I am attempting to create a REST API using the MEAN stack, and in an effort to simplify things, I have been utilizing the following resource: https://github.com/florianholzapfel/express-res ...

Nuxt2 is not compatible with the current Long-Term Support version of Node (v18)

As a newcomer, I am embarking on my first Vue.js project with Nuxt. After executing "npm run dev" in the command prompt and running "npm install" for my project, I encountered the following: * Client ██████████████████ ...

Consistent user interface experience for both Electron and browser users

Can the same index.html file be used by both an Electron process and a browser like Chrome? I have created an app that has its own Hapi server to handle HTTP requests to a database, which is working fine. However, when I try to serve the index.html file f ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

Upgrading object based on dynamic data shifts in Vue using Vuex

My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correc ...

Configuring Node.js HTTPS to function alongside HAPROXY

My goal is to establish communication between my nodejs app and HAPROXY using HTTPS. The plan is for nodejs to send a message to haproxy via https, and haproxy will then route the message accordingly. Initially, I had success with the request.js library, ...