[英]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. 不确定我是否完全以写的方式进行操作,这是第一次编写文档更新REST api调用的尝试。
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. 我希望api调用仅提供他们要更新的文档的字段,因此我将检查每个字段是否有数据,然后添加它,或者忽略,以免字段为空。
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: 这是要提交的req.body的内容:
{
"properties":
{
"name": "Ted"
}
}
Server Error calls out the first if statement and fails. 服务器错误调出第一个if语句,但失败。
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.
如果有人有更好的方法的例子,我全神贯注。
It is showing the error
because object.geometry
is not defined. 由于未定义
object.geometry
,因此显示error
。 thus it is coming as undefined
, when you are trying to assign value to object.geometry.coordinates
. 因此,当您尝试将值分配给
object.geometry.coordinates
时,它就像undefined
。
you need to define object
and object.geometry
as an object({})
Type, only then you will be able to use dot notation (.). 您需要将
object
和object.geometry
定义为object({})
类型,然后才可以使用点符号(。)。 Same thing is with object.properties
, you need to define it as an object({})
type. 与
object.properties
相同的是,您需要将其定义为object({})
类型。
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. req.body
中没有对象作为geometry
对象,因此req.body.geometry
是undefined
,这就是它req.body.geometry
该错误的原因。 first you need to check if req.body.geometry
exists, and then go for req.body.geometry.coordinates
首先,您需要检查
req.body.geometry
存在,然后再查询req.body.geometry.coordinates
use this: 用这个:
if (req.body.geometry && typeof req.body.geometry.coordinates !== undefined){...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.