What is the best way to transform an array of string values into numeric values for a Mongoose schema that includes several numeric fields?

Having an issue with a MongoDB collection named 'sold' that contains both string and numeric fields.

    const soldSchema = new Schema(
  {
    sku: String,
    hsn: String,
    qty: Number,
    article: String,
    mrp: Number,
    disc: Number,
    taxrate: Number,
    tax: Number,
    total: Number,
    orderid: String,
  },
  { collection: "sold", timestamps: true }
);
const Sold = mongoose.model("sold", soldSchema);
module.exports = { Customer, Stock, Sold, Order };

'Customer', 'Stock', and 'Order' are also defined within the same module.

Data for the sold schema is received from the frontend as an array of objects:

[
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  },
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  },
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  }
]

The above array represents req.body when logged using console.log(req.body).

When all fields in the soldSchema are set to type 'String', data gets inserted successfully in one go.

However, having issues when changing certain fields to Numbers in the schema. Seeking assistance on how to resolve this matter.

async function insertManySold(req, res) {
  let items = req.body;
  try {
    let result = await model.Sold.insertMany(items);
    res.json(result);
  } catch (error) {
    res.json(error);
  }
}

Researching online has not provided a solution so far. Your help would be greatly appreciated.

Answer №1

Your previous method may not handle strings with alphabets correctly, as converting them to Number will result in NaN. A better approach is shown below:

const object1 =  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  }

const data = {}

for (const [key, value] of Object.entries(object1)) {
  
  const temp_value = Number(value)

  // Check for NaN and 0
  data[key] =  temp_value ? temp_value : temp_value == 0 ? 0 : value
  
}

console.log(data);

The alternative code snippet below demonstrates issues that can occur with your initial implementation:

let items=
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops', // This key contains alphabet characters
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  }

    let data = {}
    for ( let key in items ) {
      data[key] = Number(items[key])
    }
console.log(data)

Answer №2

When I originally posted this question, my knowledge of JavaScript was very limited and I struggled to think like a programmer. However, the solution is actually quite simple. All you need to do is parse the object (req.body) again by creating a new object and inserting all the values through a loop. Here's how you can achieve that:

let items = req.body;
    let data = {};
    for (let key in items ) {
      data[key] = Number(items[key]);
    }

If req.body contains any numerical values, they will be parsed into numbers and stored in the new object 'data'.

This approach worked for me, but if there are alternative methods to achieve the same result, please feel free to share them with me here.

Thanks.

Answer №3

The best approach would be to address this issue directly from the front-end. Otherwise, you will need to convert each known Number key individually, as the Number function will only convert strings with numeric values into Numbers and data with characters into NaN.

Furthermore, since you are currently storing sku, hsn, orderId as Strings, they will be converted into numeric values by the Number function. Therefore, it is highly recommended to handle this conversion directly from the frontend.

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

Can I employ a PHP script as a "server" for a React application?

As I am using shared hosting without Node installed, I can't utilize Express as a server (or any other node-related features xD). The issue arises when fetching data from the Behance API in my app and encountering a CORS error. To address this probl ...

Gather information on a webpage

I am attempting to extract a table from the following page "https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Historical-Monthly?sc_lang=en#select1=0&select2=0". After using the inspect/network function in Chrome, it appears that the data ...

Toggling Legends in D3.js interactivity

My line graph displays nested data with user-selected keys. Each key has 4 child values, each represented by a line on the graph. If 2 keys are selected, there will be a total of 8 lines on the graph. I've created a legend that shows the child value ...

Unable to reset the input value to an empty string

I have created a table with a search bar feature that filters the data when the search button is clicked and resets the filter to show unfiltered data when the clear button is clicked. However, the current input value is not clearing from the display even ...

Automated image transition

I had an idea to create a script that would automatically update the graphics on an element, but I hit a roadblock and now I'm stuck on what to do next. The script is supposed to fetch data from the database and include information about: File paths ...

To modify the text within the pagination select box in ANTD, follow these steps:

Is it possible to modify the text within the ant design pagination select component? I have not been able to find a solution in the documentation. I specifically want to replace the word "page" with another term: https://i.sstatic.net/w55hf.png ...

We're sorry, but there seems to be an issue with locating the module: 'react-scroll-horizontal'

Encountering the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/react npm ERR! reac ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Calculate the total cost for each row in a table by multiplying the quantity and price using jQuery, then display the result

I'm encountering an issue with my table row calculations involving price and quantity. The calculation results show up correctly in the console, but when I try to display them back on the table, the total sum of the first row gets duplicated into all ...

Create a dynamic HTML table in React by leveraging arrays

I am working with two arrays: headings=['title1','title2'] data=[['A','B'],['C','D']] How can I efficiently convert this data into an HTML table that is scalable? title1 title2 A B ...

Positioning a Three.js static CSS2DObject with respect to the camera's perspective

I am currently working on a unique program visualizer that utilizes Three.js to showcase various aspects of a program to the user. One crucial feature of this visualizer is allowing users to click on specific objects to view additional information about th ...

Using JSON parsing to dynamically create classes with preloaded background images

Today, I successfully deployed my browser game using MVC4 to my website for the first time. I am currently navigating through the differences between running the site off of localhost and running it from the actual website. My process involves loading all ...

The loading of charts and animations is sluggish on mobile devices

My Chart.js chart starts with 0 values and updates upon clicking submit to load data from an external database. While this works efficiently on a computer browser, the load time is significantly longer when accessing the page on a mobile device. It takes a ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Upgrading from V4 to React-Select V5 causes form submission to return undefined value

Looking to upgrade from react-select v4 to v5. The form/field currently functions with v4 and Uniform, producing an output like this: { "skill": { "value": "skill1", "label": "Skill 1" } } After attempting the upgrade to V5, I'm getting a ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Displaying multiple div elements when a button is clickedLet multiple divs be

ISSUE Hello there! I'm facing a challenge where I need to display a div when a button is clicked. The issue arises from having multiple divs with the same class, making it difficult for me to target each individual div... Image1 Image2 Desired Outco ...

How can I access my API by connecting Node.js to MongoDB remotely?

I have been working on developing an application using Node.js, Express, and MongoDB. I followed some teamtreehouse tutorials to set up Node.js and MongoDB on a Digital Ocean Server. However, when trying to access my API through various URL variations, I e ...

React Native encountered an issue loading the configuration for your project

I'm having trouble creating a react native app. Every time I run the command "npx react-native init newProject", I encounter an error. Can someone assist me with creating a react native app and troubleshooting the recurring errors? strong texthttps:/ ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...