繁体   English   中英

更新Mongoose文档失败TypeError:无法读取未定义的属性“ coordinates”

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

不确定我是否完全以写的方式进行操作,这是第一次编写文档更新REST api调用的尝试。

我希望api调用仅提供他们要更新的文档的字段,因此我将检查每个字段是否有数据,然后添加它,或者忽略,以免字段为空。

如您所见,我都尝试过检查该字段是否未定义或该字段是否存在,它们都导致相同的服务器错误。

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);
    });
});

这是要提交的req.body的内容:

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

服务器错误调出第一个if语句,但失败。

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

第一个问题是我可以检查未定义的属性以将其跳过吗? 我应该完全这样吗? 如果有人有更好的方法的例子,我全神贯注。

由于未定义object.geometry ,因此显示error 因此,当您尝试将值分配给object.geometry.coordinates时,它就像undefined

您需要将objectobject.geometry定义为object({})类型,然后才可以使用点符号(。)。 object.properties相同的是,您需要将其定义为object({})类型。

更换:

var object;

带有:

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

一切都会对您有效。

更新:

req.body中没有对象作为geometry对象,因此req.body.geometryundefined ,这就是它req.body.geometry该错误的原因。 首先,您需要检查req.body.geometry存在,然后再查询req.body.geometry.coordinates

用这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM