2

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!

2
  • Is it a requirement to POST multiple arrays at the same time, or could you pass one array that has all the detail objects in it? Commented Jul 9, 2020 at 1:59
  • yes it is, since this form is for customer invoice . a customer could pick all the size option (S M L XL XXL XXXL) at one transaction/input Commented Jul 9, 2020 at 6:34

1 Answer 1

2

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]
  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, can you tell me how to get req.body.details ? since there is no input has that name attribute. and for the Schema , if i put String type it will send me error "cast to string failed for value" since i submit multiple array at the same time.
Sure, I edited the answer. Have a look. With this you could still keep the validation for types in place I believe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.