Backbone .save() 上的 404 错误

404 Error on Backbone .save()

跟我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);

The Mongoose .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",
            });

您需要在模型中设置 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",
});