簡體   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