2013-10-29 142 views
0

我有一個演示Backbone應用程序在REST的後臺使用Node。在骨幹功能之一,我檢索一個集合的模式,並顯示一個表單編輯模型這樣創建新記錄而不是更新現有記錄

var toEdit = this.menuItems.get(baz); 
    this.editFormView = new EditForm({model: toEdit}); 
    $('#formdiv2').html(this.editFormView.render().el); 

這是工作的罰款。該模型在窗體中顯示。在表單視圖中,我有一個函數來設置新的模型數據並在提交表單時保存它,但是,當我單擊提交時,它將創建一條新記錄,而不是更新表單中顯示的記錄。

你能從下面的代碼中看到爲什麼會發生這種情況嗎?

由於它創建了一條新記錄,app.post方法在節點後臺被調用,但它應該是app.put方法。

app.post('/sentences', function (req, res){ 

    var wine = req.body; 
    console.log('Adding wine: ' + JSON.stringify(wine)); 
    db.collection('english', function(err, collection) { 
     collection.insert(wine, {safe:true}, function(err, result) { 
      if (err) { 
       res.send({'error':'An error has occurred'}); 
      } else { 
       console.log('Success: ' + JSON.stringify(result[0])); 
       res.send(result[0]); 
      } 
     }); 
    }); 

}) 

app.put('/sentences/:id', function(req, res){ 

    var id = req.params.id; 
    var wine = req.body; 
    delete wine._id; 
    console.log('Updating wine: ' + id); 
    console.log(JSON.stringify(wine)); 
    db.collection('english', function(err, collection) { 
     collection.update({'_id':new BSON.ObjectID(id)}, wine, {safe:true}, function(err, result) { 
      if (err) { 
       console.log('Error updating wine: ' + err); 
       res.send({'error':'An error has occurred'}); 
      } else { 
       console.log('' + result + ' document(s) updated'); 
       res.send(wine); 
      } 
     }); 
    }); 
}) 

這是骨幹模型和收集

var MenuItem = Backbone.Model.extend({ 

    idAttribute: "_id", 
    // idAttribute: "question", 

    urlRoot: '/sentences' 

}); 


var MenuItems = Backbone.Collection.extend({ 
    comparator: 'question', 
    model: MenuItem, 
    url: '/sentences' 
}); 

這些都是在形式視圖中保存,並設置數據的方法。

save: function() { 

    this.setModelData(); 

    this.model.save(this.model.attributes, 
     { 
      success: function (model) { 
       console.log(model); 
       // app.views.pippa.menuItems.add(model); 
       // app.navigate('menu-items/' + model.get('url'), {trigger: true}); 
      } 
     } 
    ); 
}, 

    setModelData: function () { 
     console.log(this.model); 
     this.model.set({ 
      name: this.$el.find('input[name="name"]').val(), 
      category: this.$el.find('input[name="category"]').val(), 
      _id: null, 
      url: this.$el.find('input[name="url"]').val(), 
      imagepath: this.$el.find('input[name="imagepath"]').val(), 
      uk: this.$el.find('input[name="uk"]').val(), 

     }); 
    } 

回答

0

問題是_id設置爲null。只是拿出那條線,它會工作

setModelData: function () { 
     console.log(this.model); 
     this.model.set({ 
      name: this.$el.find('input[name="name"]').val(), 
      category: this.$el.find('input[name="category"]').val(), 
      _id: null, 
      url: this.$el.find('input[name="url"]').val(), 
      imagepath: this.$el.find('input[name="imagepath"]').val(), 
      uk: this.$el.find('input[name="uk"]').val(), 

     }); 
    }