2014-01-28 18 views
0

我的骨幹型號:未分配給模型的主幹模型ids,也未分配給模型的集合url屬性。模型是贈品認爲新

var Location = Backbone.Model.extend({ 

    idAttribute: "_id", 

    // Default attributes ensure that each todo created has `title` and `completed` keys. 
    defaults: { 
     nick_name: null, //Example: The Office 

     street_address: '214 West 29th Street', 
     extended_address: null, // Example: Suite 205 
     cross_street: null, 
     locality: 'New York', 
     region: 'NY', 
     postal_code: 10001, 
     country: 'United States', 

    }, 

    initialize: function() { 
    } 

    }); 

我的骨幹收集:

var LocationCollection = Backbone.Collection.extend({ 

    // Reference to this collection's model. 
    model: Location 

    }); 

我有一個全局變量,它是模型JSON數組:

json_data = [{country: "United States of America", 
cross_street: "", 
extended_address: "", 
id: 3, 
locality: "Brooklyn", 
nick_name: "", 
postal_code: 11208, 
region: "NY", 
street_address: "3039 Fulton street"}] 

當我嘗試將模型屬性數組添加到集合中,模型始終被視爲新模型而不是保存到數據庫。因此,我嘗試調用保存在任何模型上,我得到一個POST請求,而不是一個PUT請求。此外,我已經嘗試使用模型集方法創建沒有集合的模型,並且儘管我可以調用model_instance.attributes方法並且我看到該id是輸出。從控制檯日誌

this.locationCollection = new LocationCollection(); 
     this.locationCollection.url = urlRoot; 
     this.locationCollection.add(json_data); 

     this.locationCollection.each(function(model, index, option) { 
     console.log(model.id); 
     console.log(model.urlRoot) 
     console.log(model.url) 
     console.log(model.attributes); 
     }, this) 

輸出:

不確定
不確定
一些功能網址
{國家: 「美國」, CROSS_STREET: 「」, extended_address: 「」, 「NY」, street_address:「3039 Fulton street」} //正確的預期輸出model.attributes

請告訴我,如果我正確地將模型添加到集合。

回答

0

我認爲這肯定與您在Location模型中設置的idAttribute屬性有關。你有id3json_data但你已經設置idAttribute_id,所以什麼可能發生的是,因爲json_data沒有_id它是undefined,它會被設置爲模型的id所以模型id變得undefined。現在,由於idundefined保存模式,它會將其視爲新模型併發出POST請求。

doc

idAttribute model.idAttribute

模型的唯一標識符存儲在id屬性下。如果 你直接與後端(CouchDB的,MongoDB的),其 使用不同的唯一密鑰通信,你可以設置一個型號的idAttribute到 透明地從鑰匙ID映射。

FIX:

要麼你刪除idAttribute您已設置爲_id或屬性_id添加到您的json_data

+0

謝謝,這解決了我的問題。 – user2183536

+0

太好了。歡迎.. –