![](/img/trans.png)
[英]MongoDB save() creating new document each time rather than updating existing document
[英]creating new record rather than updating existing record
我有一个在后台使用Node进行REST的演示Backbone应用程序。 在其中一个Backbone功能中,我从集合中检索模型并显示表单以编辑模型,如下所示
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(),
});
}
问题是_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(),
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.