Search code examples
javascriptnode.jsobjectpostpug

Accessing attributes of an object in body is not possible "undefined"


I have a very strange, to my point of view, problem. I am doing a post request in my Node.js application. I pass a form where one of the variables is an object place:

{"id":"0ba78ba1-c7dc-440f-b166-4b2cd6dceff0","coordinates":{"crs":{"type":"name","properties":{"name":"EPSG:4326"}},"type":"Point","coordinates":[25.28827329151016,54.69353842802546]},"place_name":"Viva Pizza & Sushi & Wok                                                                                                        ","description":"Sushi and pizza based fast food restaurant","category":"Food","createdAt":"2021-03-17T13:25:27.619Z","updatedAt":"2021-03-17T13:25:27.619Z"}.

The problem is that i can access it as req.body.place in my function but when I try to get

req.body.place.id

id is undefined. In contrast, accessing req.body.user.id in the same way is fine. What am I doing wrong here? Accessing object attributes seems quite straightforward but it does not work in this case. Any suggestions will be helpful.

Some more code is below:

backend function:

exports.likePlace = async function (req, res) {
    const user = await models.User.findOne({
    where: {
            id: req.user.id
        }
    });
    const place = await models.Place.findOne({
        where: {
            id: req.body.place.id
        }
    });
    try {
        await user.addPlace(place, { through: { selfGranted: false } });
        res.send(true);
    }
    catch (e) {
        console.log(e);
        res.send(false);
    }
}

Making the post request:

input(type="hidden" name="place" value=places[0])
                    button#nope(type="submit")

Solution

  • Just use id like value in your input:

    input(type="hidden" name="place" value=places[0].id)
    button#nope(type="submit")
    
    // ...code
    const place = await models.Place.findOne({
      where: {
        id: req.body.place
      }
    });
    // ...code