My form data array isn't POSTing to my mongodb the way I want it to

19 views
Skip to first unread message

blue wolf

unread,
Jun 25, 2016, 10:39:14 PM6/25/16
to nodejs
My array in my MongoDB is not being structured the way I want it to be. I am using node.js, Express, and Mongoose.
.
Here is my schema:

   
var fruitSchema = new schema ({
        fruitName
: {type: String},
        priceArray
: {type: Array}
   
});



Here is part of the code that pushes new priceArray items:

   
Fruit.findOneAndUpdate({fruitName: req.body.fruitName},
               
{
                $push
: {
                    priceArray
: {
                        price
: req.body.price,
                        description
: req.body.description
                   
}
               
}
           
}



And here is the form:

   
 <form method="POST" action="/fruit">
   
<div class='form-group'>
       
<label for="fruitName">Fruit Name</label>
       
<input type="text" name="fruitName" id="fruitName"/>
   
</div>
   
<div>
       
<label for="price0">Price</label>
       
<input type="text" name="price[0]" id="price0"/>
       
       
<label for="description0">Description</label>
       
<input type="text" name="description[0]" id="description0"/>
   
</div>
   
<div>
       
<label for="price1">Price</label>
       
<input type="text" name="price[1]" id="price1"/>
       
       
<label for="description1">Description</label>
       
<input type="text" name="description[1]" id="description1"/>
   
</div>
   
<input type="submit" value="submit">
   
</form>



So what's all this saying? Basically, a user can enter a name of a fruit, and then they would enter the **price** of the fruit, and give a **description**. So the **'price'** and **'description'** pieces are always together. The form allows for multiple inputs of price/description pairs (the example form I've posted here allows for 2 pairs, but the real form allows for unlimited pairs).

In my MongoDB, this is how the above code inserts the form data:

   
 {
   
"fruitName" : "test fruit",
   
"priceArray" : [
       
{
           
"price" : [
               
"$2.00",
               
"$3.00"
           
],
           
"description" : [
               
"Good",
               
"Bad"
           
]
       
}



Here is how I **want** it to look like:

   
 {
   
"fruitName" : "test fruit",
   
"priceArray" : [
       
{
           
"price" : "$2.00"
           
"description: "Good"
        }
        {
            "
price" : "$3.00"
            "
description" : "Bad"
        }
        ]
    }



How can I fix this?
Reply all
Reply to author
Forward
0 new messages