1

I have been having trouble with this for a while.

I created a mongoose model, and have had plenty of successes using JSON and req.body to save data to the mongodb database through postman.

However, I am attempting to use arrays for the first time and I am running into trouble.

(I am using express and node.js btw)

My server has the following setup to receive the post route:

router.post('/data', function(req, res){
    var data = new Data({
        name: req.body.name,
        price: req.body.price,
        array: [{
            name: req.body.array[0].name, 
            username: req.body.array[0].username,
            bio: req.body.array[0].bio,
            languages: [{language: req.body.array[0].languages[0].language}]
        }]...

I have tried this with and without the [0] before each array name. All of the values that are not arrays save fine to the database, but the arrays all have only one attribute, and that is the _id and a bunch of jibberish after that.

My JSON is correct from what I have read..

{
    "name": "Bill",
    "price": 290,
    "array": [{
        "name": "Danny", 
        "username": "dnnyboy",
        "bio": "Helo hello",
        "languages": [{"language": "English"}]
    }],...(the JSON list continues)

How do I properly save JSON array data into a mongoose model using req.body? What is the syntax I am missing?

parwatcodes
  • 6,669
  • 5
  • 27
  • 39
Tristan C
  • 593
  • 2
  • 7
  • 16
  • Please show your schema. I suspect there is something wrong with the schema definition and the way you are assigning values. Otherwise, whatever you are doing should have worked. – Ankit Gomkale Apr 06 '17 at 06:39

2 Answers2

0

Pass the req.body to your Data like this

var data = new Data(req.body);

Reference: Passing model parameters into a mongoose model

Community
  • 1
  • 1
vpdeva
  • 303
  • 2
  • 11
0

Pass the req.body in the form of data that you are showing

{ "name": "Bill", "price": 290, "array": [{ "name": "Danny", "username": "dnnyboy", "bio": "Helo hello", "languages": [{"language": "English"}] }]

and use

var data = new Data(req.body);