Alex ROJAS
Alex ROJAS

Reputation: 57

How to post an Array from Textarea to mongoDB?

I'm trying to POST an Array of serial numbers, but once it's posted, all the serial numbers added in the textarea are posted together as a single String.

This is my form:

<form class="" id="serialsForm" action="/serialsnew" method="post">
 <h5 style="text-align:center">Procesar RMA</h5>

  <input placeholder="Product ID"class="input1" type="text" 
  name="productId" value="">

  <textarea id="textAreaSerial" class="newSeriales" placeholder="# 
  Seriales"name="serial[]" rows="3" cols="80" ng-trim="false"> . 
  </textarea>


  <button  type="submit" value="send" class="btn btn-primary 
   buttonNewRma" data-toggle="modal"  id="submit">
  submit
  </button>

</form>

this is my post request

 app.post("/serialsnew", function(req, res){
 var productId = req.body.productId;
 var serialNum = req.body.serial;

Seriales.create({
 product: productId,
 seriales: serialNum,

  }, function(err, serial){
    if(err){
      console.log("we coulndt add the serial numbers")
     } else{
      console.log("we just added a patch of serials")
     }
  })
  res.json(req.body);
  // res.redirect("/serialsnew")
  })

This is how my array looks like on my res.json

enter image description here

I'm trying to create an input of serial numbers so we can track warranty time. An example of how i would like to store the data is below.

{
productId: "laptops",
serial: [
11111,
22222, 
44444,
 ]

}

Upvotes: 3

Views: 951

Answers (1)

Ray
Ray

Reputation: 3959

That's probably happening because you're using a textarea, which is meant for string data.

How about modifying the data like this?

//this is basically your req.body, with sample serial values
var req = {body: {serial:["2423,23423"]}};

var stringGroup = req.body.serial[0];
var serial = stringGroup.split(",").map(Number);

console.log(serial);

Upvotes: 1

Related Questions