Passing array in request body in node express js

Issue

I have an array that I would like to pass in my request body for a POST request. If successful, a new document should be inserted into MongoDB. Here is my code so far:

app.post(`/api/add`, async (req, res) => {
    collection.create( {  'id': req.body.id, 
                        'name': req.body.name, 
                        'date': req.body.date,
                        'groups': [
                            { 'id': req.body.groups.id, 'title': req.body.groups.title, 'teamMemberIds': [ req.body.groups.teamMemberIds] }]
                    }, 
    (err, result ) => {
        if (err) {
            console.log('error', err)
        } else {
            console.log('updated', result);
            res.status(200).send(result);
        }
    })
});

I am sending the request body in postman like so:

{
    "id": "1",
    "name": "Saved Team 1",
    "date": "1/1/20",
    "groups": [
        {"id": "group-1", "title": "test saved group 1", "teamMemberIds": ["bpumper", "jdoe"] },
        {"id": "group-2", "title": "test saved group 2", "teamMemberIds": ["bsimmons", "ljames"] },
    ]
}

Here is my mongoose schema:

const savedTeamSchema = new Schema({
    id: String,
    name: String,
    date: String,
    groups: [{ id: String, title: String, teamMemberIds: [String]}]
})

However, after the request is executed, this is the document that gets inserted into the collection:

{
    "_id" : ObjectId("5eed13b216b4836f406b6f63"),
    "id" : "1",
    "name" : "Saved Team 1",
    "date" : "1/1/20",
    "groups" : [ 
        {
            "teamMemberIds" : [ 
                null
            ],
            "_id" : ObjectId("5eed13b216b4836f406b6f64")
        }
    ],
    "__v" : 0
}

I cant figure out how to get the group object to get added into the groups array. What am I missing?

Solution

 { 'id': req.body.groups.id, 'title': req.body.groups.title, 'teamMemberIds': [ req.body.groups.teamMemberIds] }]

You cannot access fields of array’s elements like this: req.body.groups.id, req.body.groups.title and req.body.groups.teamMemberIDs. In order to get the fields in the nested array you would have to do something like this req.body.groups[index].id.

But doing all of that is not necessary, since your req.body and mongoose schema are the same you can simply pass in the whole req.body.groups into groups like shown below.

app.post(`/api/add`, async (req, res) => {
    collection.create( {  'id': req.body.id, 
                        'name': req.body.name, 
                        'date': req.body.date,
                        'groups': req.body.groups //change this line of code.
                    }, 
    (err, result ) => {
        if (err) {
            console.log('error', err)
        } else {
            console.log('updated', result);
            res.status(200).send(result);
        }
    })
});

Or even better you could just add the entire req.body to collection.create()

app.post(`/api/add`, async (req, res) => {
    collection.create(req.body, 
    (err, result ) => {
        if (err) {
            console.log('error', err)
        } else {
            console.log('updated', result);
            res.status(200).send(result);
        }
    })
});

In case when your req.body and mongoose schema have different formats, then for the array parts you can use the array method map to change the array format prior to document creation.

Answered By – Sihoon Kim

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published