Map Backbone" save" Mongoose" post"

时间:2014-05-19 20:59:06

标签: node.js mongodb post backbone.js mongoose

如何使用Mongoose API同步Backbone模型?我正在客户端使用Backbone.js开发Node.js SPA,在服务器端使用Express和Mongoose。我已经使用Mongoose设置了一个api,当我从控制台发布到数据库时,它可以工作。另外,我有一个Backbone视图,它在客户端保存模型。

我在哪里添加代码将两者映射到一起?在我的Backbone视图中?还是在模特?如何将服务器端变量拉入客户端?

这是代码:

骨干视图:

var ProductDetailsView2 = Backbone.View.extend({

    initialize: function() {

    this.listenTo(this.model, "change", this.render);

},

render: function() {        

    $(this.el).html(_.map([
        '<a href="#/shopping-cart">Back to Store</a>' +
        '<form>' +
        '<h3>' + this.model.get('title') + '</h3>'+
        '<img src="photos/kitty-store/' + this.model.attributes.imagepathsm + '" class="img-polaroid" style="width:150px; max-height:100px; overflow:hidden;"/>' +
        '<span class="label">' + 'Quantity: ' + '</span>' + 
        '<input class="quantity" name="quantity" value="' + this.model.get('quantity') + '">' +
        '<button type="button" class="btn btn-primary">Save Quantity</button><br/>' +
        '<span class="price">' + '$' + this.model.get('price') + '.00' + '</span><br/>' +
        '</form>' +
        '<span class="description">' + this.model.get('description') + '</span><br/>' +
        '<a href="#/orders/' + this.model.attributes._id + '">Add to shopping-cart</a>', this.model.calculateAmount(),

    ], function(val, key) {
        return '<li class="shopping-item">' + val + '</li>';    

    }));

    this.delegateEvents({
        'click .btn-primary' : 'save'
    })

    return this;
},

save: function() {
    this.setModelData();

        this.model.save(this.model.attributes,
        {
            success: function (model) {
                app.productsOrderedCollection.add(model);
                //can we ajax post here to the server???

            }
    }
        )
},

setModelData: function() {
    this.model.set({
        quantity: this.$el.find('input[name="quantity"]').val()

    })

  }
 });

骨干模型:

var SupplyCategory = Backbone.Model.extend({

urlRoot: '/api/products',
idAttribute: "_id",
defaults: {

            "product_id": 3,
            "category": "supplies",
            "title": "Big Max Fountain",
            "id": "big-max-fountain",
            "url" : "big-max-fountain",
            "name": "Big Max Fountain",
            "keyword" : "Hydration",
            "description" : "Large capacity drinking fountain",
            "price" : "400",
            "quantity" : "2",
            "imagepathsm" : "big-max-fountain.jpg" 


        },



    calculateAmount: function () {
        return '<p class="total">' + 'Total: $' + this.get('price') * this.get('quantity') + '.00';
    },
});

发布到MongoDB:

//create a single product
app.post('/api/products', function (req, res) {
   var product;
   console.log("POST: ");
   console.log(req.body);
   product = new ProductModel ({
   id: req.body.id,
   category: req.body.category,
   title: req.body.title,
   url: req.body.url,
   keyword: req.body.keyword,
   description: req.body.description,
   price: req.body.price,
   quantity: req.body.quantity,
   imagepathsm: req.body.imagepathsm,
   modified: req.body.modified,

});
 product.save(function(err) {
    if (!err) {
     return console.log('added');
   } else {
    return console.log(err);
  }
});
  return res.send(product);
});

1 个答案:

答案 0 :(得分:0)

这是我的答案。我不得不抓取我想发布到服务器的模型数据,将其保存到变量中并将其发布在Backbone视图中的save函数的成功回调中。以下是ProductDetailsView2的更新保存功能:

save: function() {

    this.setModelData();

        this.model.save(this.model.attributes,
        {
            success: function (model) {

                app.productsOrderedCollection.add(model);

                //Post to the ordered Supplies Collection
                jQuery.post("/api/orders", {
                    "title": title,  
                    "description": description, 
                    "quantity" : quantity,
                    "price" : price 

                }, function (data, textStatus, jqXHR) { 
                    console.log("Post response:"); console.dir(data); console.log(textStatus); console.dir(jqXHR); 
                });

            }

    })
         var description = this.model.get('description');
        var title = this.model.get('title');
        var quantity = this.model.get('quantity');
        var price = this.model.get('price');
},