2013-10-29 144 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(), 

     }); 
    }