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

151
Visualizações
How to convert an array of strings values to numeric values for Mongoose schema containing few numeric fields?

My problem is that, I have a MongoDB collection named 'sold', which contains some string fields and some 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 };

The 'Customer', 'Stock', and 'Order' are other schema are in the same module.

For the sold schema, I received the data from the front end, which is an array of objects like this as shown below:

[
  {
    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 is the result of req.body i.e. console.log(req.body)

If I change all the fields to type 'String' in soldSchema, then all the values get inserted in a single go.

This function works fine with all string values in the schema.

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);
  }
}

But, if I change the data types to Numbers for some fields in the schema as mentioned above, then it doesn't work. Please let me know how to achieve this.

I have searched many articles on the web but could not find the answer. Could you please help me?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your above code won't work for string contains characters like (abc...z), Number will convert any string which contains alphabets to NaN, you should try this way instead.

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)

  // Here we are checking for NaN and 0
  data[key] =  temp_value ? temp_value : temp_value == 0 ? 0 : value
  
}

console.log(data);

Your way will give this error run below code

let items=
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops', // Look for this key
    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)

about 4 years ago · Juan Pablo Isaza Relatório

0

when i posted this question i was very new in javascript, so i couldn't think of it like a programmer, the answer is very simple, all you have to do is to parse the object i.e. req.body again. i mean to say, make a new object and insert all the values in it via looping over req.body. like this.

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

if the req.body has any numerc value it will get parsed into numbers and get stored in the new object data.

this solution worked for me if there is any other approach for the same, please share it with me here.

tanks.

about 4 years ago · Juan Pablo Isaza Relatório

0

I suggest this should be handled from front-end directly. Otherwise you need to convert for each known Number key, because this Number will convert, each string which has numeric values into Number. string with char. data into NaN.

and, as you are storing sku,hsn,orderId in String, but Number will convert into numeric value. so i strongly suggest handle this from frontend directly.

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