【问题标题】:404 Error on Backbone .save()主干 .save() 上的 404 错误
【发布时间】:2015-01-13 17:44:58
【问题描述】:

这与我的 URL 的 /:id 结尾有关;我想我的 Mongoose 和 Backbone ID 字段无法正确匹配。这是完整的控制台错误POST http://localhost:8080/api/bears/:id 404 (Not Found)

这是我save()我的模型的视图。

var HomeView = Backbone.View.extend({
            el:$('#main'),

            render: function(){

                this.template = _.template($('#home_template').html());

                this.$el.html(this.template);

                $('#new-entry').submit(function(ev){

                    var entry = new Entry({task: $('#word').val(), description: $('#definition').val() });

                    dictionary.add(entry);

                    entry.save();

                    console.log(dictionary.toJSON());

                    $('#body').children('input').val('');

                    return false;

                });

            }
        })

这是我的猫鼬模式:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectID = Schema.ObjectID;

var EntrySchema = new Schema({
    task: String,
    description: String
});

module.exports = mongoose.model('Entry', EntrySchema);

猫鼬.post()路线我的目标:

router.route('/bears')
//create a bear
.post(function(req, res){
    var entry = new Entry();

    entry.task = req.body.task;
    entry.description = req.body.description;

    entry.save(function(err){
        if(err)
            res.send(err);

        res.json({message: 'task created'});
    })
});

这是我的模型定义:

var Entry = Backbone.Model.extend({

                urlRoot: '/api/bears/',

                defaults: function(){
                    return{

                        task: '',
                        description: ''
                    }
                },

                parse: function(response){
                    response.id = response._id;
                    return response;
                },

                idAttribute: "_id",
            });

【问题讨论】:

    标签: javascript node.js mongodb backbone.js


    【解决方案1】:

    您需要在模型中设置urlRoot

    var Entry = Backbone.Model.extend({
    
      urlRoot: '/api/bears/',
    
      defaults: function(){
          return{
              task: '',
              description: ''
          }
      },
    
      parse: function(response){
          response.id = response._id;
          return response;
      },
    
      idAttribute: "_id",
    });
    

    【讨论】:

    • 我的模型存在于一个集合中,但我认为 urlRoot 是用于独立模型(集合之外)。我添加了 urlRoot,但它没有用。那我在哪里指定/:id url呢?
    • id 是由主干使用模型的idAttribute 添加的,默认情况下是“id”属性。主干将 url 构建为this.urlRoot + "/" + this.id
    • 如果没有负载 JSON 数据的样本,很难判断
    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2022-01-03
    • 2018-08-11
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多