How to post multiple array Nodejs

Viewed 745

I need to post multiple array at the same time so i can achieve this :

{
 name:"John Snow",
 detail: [
    {size: "M", total: 5, color: "red"},
    {size: "S", total: 2, color: "black"}
 ]
}

i'm using dynamic form that can generate new input field for detail array. so this is my schema model :

const OrderSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    detail:[{
        size:{},
        color:{},
        total:{}
    }],
    date:{
        type: Date,
        default: Date.now
    }
});

this is my route post :

router.post('/add', (req, res) => {
    let errors = [];

    if (!req.body.name) {
        errors.push({ text: 'Your customer name is empty' });
    }
    if (errors.length > 0) {
        res.render('orders/add', {
            errors: errors,
            customer: req.body.name,
            detail:[{
                size: req.body.size,
                color: req.body.color,
                total: req.body.total
            }]
        });
    } else {
        const newUser = {
            customer: req.body.name,
            detail:[{
                size: req.body.size,
                color: req.body.color,
                total: req.body.total
        }
        new Order(newUser)
            .save()
            .then(order => {
                res.redirect('/');
            })
    }
});

submit post is work, it just the result is not what i want :

{
 name:"John Snow",
 detail: [
    {size: ["M","S"], total: [5,2], color: ["red", "black"]}
 ]
}

i hope you can help me, thanks!

1 Answers

Let's assume you have your details in a request body.

The req.body.details would look like this:

 details: [
    {size: "M", total: 5, color: "red"},
    {size: "S", total: 2, color: "black"}
 ]

You could then simply save it altogether like so:

detail: req.body.details

Note that your Schema for details is a bit odd:

detail:[{
    size:{}, // seems to be a string not an object
    color:{}, // seems to be a string not an object
    total:{} // seems to be a number not an object
}]

Instead, I think you could do:

detail:[{
   size:{type: String},
   color:{type: String}, 
   total:{type: Number} 
}]

Edit:

Since you do not seem to validate the details, you could simply make it an array in your Schema (that is up to you and what works best).

detail: { type: Array }

In general req.body.details could come from wherever you make the request. It could be sorted and equal to the array that you want to save in the database.


I am not fully aware of what is in your req.body.size for example but if it is an array such as ["M","S"] then you would extract each element and create separate objects that you would then push to the array which you would be saving in your database.

Have a look below:

let size = ["M","S"]
let total = [5,2]
let color = ["red", "black"]
    
let detailsToDb = []
for (let i=0; i<size.length; i++) {
   detailsToDb.push({
     size: size[i],
     color: color[i],
     total: total[i]
   })
}
console.log(detailsToDb)

In your case you could use req.body.size[i] etc. right away, no need to initialize the variables.

let detailsToDb = []
  for (let i=0; i<req.body.size.length; i++) {
    detailsToDb.push({
      size: req.body.size[i],
      color: req.body.color[i],
      total: req.body.total[i]
  })
}
Related