Can not post the nested object json to node express body parser
Asked Answered
A

1

5

Hi I'm creating sample REST api using Node, Express and Mongo. I'm using bodyParser() middle ware to parse the form data. Its working fine for simple object say

         var user = {
             name:'test',
             age:'20'
         }

req.body produce the same set of format to save it in the mongodb like.

         {
             name:'test',
             age:'20'
         }

When using complex object

         var user = {
                 name:'test',
                 age:'20',
                 education: {
                     institute:"xxx",
                     year:2010
                 }
            }

req.body produce different format something like

           {
                 name:'test',
                 age:'20',
                 education[institute]: "xxx",
                 edcuation[year]:2010
            }

I would like to get the same format which i post in the body to save them in the database. Is this the right approach or any other method available to this?

Azotic answered 3/11, 2014 at 9:53 Comment(0)
A
9

I think it's not clear in the documentation. I've spent hours trying to find it. Anyway...

You need to change your body-parser option to extended: true as shown below.

app.use(bodyParser.urlencoded({ extended: true }));

https://github.com/expressjs/body-parser#bodyparserurlencodedoptions

Afterheat answered 7/1, 2015 at 12:33 Comment(2)
Actually, I may be having a similar issue. Server is written in node.js + Express and client is another node.js app. The schema for the collection is hierarchical and thereby a bit more complex. I tried both extended:true and extended:false and neither work. What am I missing?Freshet
I really don't know why. But I recommend you to open a new question on stack or report on github site of body-parser.Afterheat

© 2022 - 2024 — McMap. All rights reserved.