Insert embedded documents Mongo DB from express app

1.6k views Asked by At

I have a mongo db schema like so

users:
{username:"",
 age: "",
 data: [ 
      {field1:"", field2:""},
      {field1:"", field2:""}
]

}

My problem is how do send over my user object to my express route to post data to the db.

Typically i create my user object like so:

var user= {username:"test" age: 20};

and send this user object with my ajax call to my adduser route.

Ho do i structure my above assignment to include my embedded documents.

when i use this structure:

 sign_in_data: [{date:"",time_in:"",time_out:""}]

my database looks like this:

sign_in_data[0][date]: "",
sign_in_data[0][time_in]: "",
sign_in_data[0][time_out]: ""

but it should look like this:

sign_in_data: [
{
   date: "2015-06-08",
   time_in: "17:35",
   time_out: "17:35"
},
]
1

There are 1 answers

2
Wilson On BEST ANSWER

at the moment when you are configuring express, review if you are using this line of code:

In case you are using Express 4.x version

Note: you need to have body-parser installed.

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

In case you are using Express 3.x version

app.use(express.urlencoded());

I did a test example where the property cars is an an array of objects send from the html file, and it is saving as you want in the database.

So this is my express server file:

// ..

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


app.post('/api/user', function (req, res) {
  var user = {
    username: req.body.username,
    age: req.body.age,
    cars: req.body.cars
  };

  db
    .collection('user')
    .insert(user, function (err, result) {
      if (err) return res.status(500).send(err);

      res.send(result);
    });
});

// ..

database data inserted:

{
    "_id" : ObjectId("5578b48f1e8cdf0520bdf76f"),
    "username" : "wilsonbalderrama",
    "age" : "29",
    "cars" : [
        {
            "name" : "Ferrari",
            "color" : "Red"
        },
        {
            "name" : "Mustang",
            "color" : "Gray"
        }
    ]
}

and my html file where I am sending the data, you can review it in this gist file: https://gist.github.com/wilsonbalderrama/62f76a348c0aa217cdd9

Hope this helps you.