roskelld
roskelld

Reputation: 1130

Update Mongoose document fails TypeError: Cannot read property 'coordinates' of undefined

Not sure if I'm at all doing this the write way, it's the first attempt at writing a document update REST api call.

I want the api call to supply just the fields of the document they want to update, so I was going to check if each field had data and then add it, or ignore if not to avoid fields being nulled.

As you can see I've tried both to check if the field was not undefined, or the field exists, they both lead to the same server error.

app.put('/api/objects/update/:_id', function(req, res)
{
    var id = req.params._id
    var object;

    if (typeof req.body.geometry.coordinates !== undefined) { object.geometry.coordinates = req.body.geometry.coordinates; }
    if (req.body.properties.name) { object.properties.name = req.body.properties.name; }


    Object.updateObject(id, object, {}, function(err, object)
    {
        if (err)
        {
            res.json(err);
            console.log("Object Not Found: " + id);
        }

        res.json(object);
        console.log("Updated Object: " + id);
    });
});

This is the contents of the req.body that's being submitted:

{
  "properties":
  {
    "name": "Ted"
  }
}

Server Error calls out the first if statement and fails.

TypeError: Cannot read property 'coordinates' of undefined
    at /opt/bitnami/apps/API/app.js:221:31

First question is can I check for an undefined property to skip it? Should I be doing it this way at all? If anyone has examples of a better way, I'm all ears.

Upvotes: 0

Views: 1791

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

It is showing the error because object.geometry is not defined. thus it is coming as undefined, when you are trying to assign value to object.geometry.coordinates.

you need to define object and object.geometry as an object({}) Type, only then you will be able to use dot notation (.). Same thing is with object.properties, you need to define it as an object({}) type.

Replace:

var object;

With:

var object={};
object.geometry={};
object.properties = {};

and everything will work fine for you.

Update:

req.body has no object as geometry inside it, thus req.body.geometry is undefined and that's why it is throwing that error. first you need to check if req.body.geometry exists, and then go for req.body.geometry.coordinates

use this:

if (req.body.geometry && typeof req.body.geometry.coordinates !== undefined){...}

Upvotes: 1

Related Questions