Home > Software design >  Parsing posted object array, Express
Parsing posted object array, Express

Time:10-20

I need to parse data with Express from form:

invoiceRouter.post('/', async (req,res) => {
  console.log(req.body);
  let invoice = new Invoice();
  invoice = req.body;
  invoice.status = 0;
  //save
  res.redirect('/invoices');
});

When I log, the array of objects is read as list of values:

{
createdDate: '2021-10-15',
invoiceRows: [ 'Title3', '2', 'Title2', '3' ]
}

But it can not read the invoiceRows as array of 2, therefore I am struggling to parse it into array for saving it. When I set the extended: false, I can see following result from req.body:

[Object: null prototype] {
  createdDate: '2021-10-15',
  'invoiceRows[0].productTitle': 'Title2',
  'invoiceRows[0].unitPrice': '2',
  'invoiceRows[1].productTitle': 'Title3',
  'invoiceRows[1].unitPrice': '2'
}

The schema I am using:

const invoiceSchema = new mongoose.Schema({
    createdDate: {
        type: Date,
        required: true
    },
    status: {
      type: Number,
      required: true
    },
    invoiceRows: [{
      productTitle: String,
      unitPrice: Number
    }]
});

Question: what am I doing wrong, in order to get array of objects from req.body inside parent object?

CodePudding user response:

In your req.body you should be receiving like bellow (As per your model schema). Make your front end to send data like bellow.

 {
   createdDate: '2021-10-15',
   invoiceRows: [ { productTitle :'Title1', unitPrice : 2}, { productTitle :'Title2', unitPrice : 3} ]
}
  • Related