redress
redress

Reputation: 1449

404 Error on Backbone .save()

It has something to do with the /:id ending of my URL; I can't get my Mongoose and Backbone ID fields to match up properly, I think. Here is the full console error POST http://localhost:8080/api/bears/:id 404 (Not Found)

Here's the view in which I save() my model.

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;

                });

            }
        })

Here's my mongoose schema:

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() route Im targeting:

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'});
    })
});

And here's my model definition:

var Entry = Backbone.Model.extend({

                urlRoot: '/api/bears/',

                defaults: function(){
                    return{

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

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

                idAttribute: "_id",
            });

Upvotes: 1

Views: 561

Answers (1)

u.k
u.k

Reputation: 3091

you need to set the urlRoot in your model:

var Entry = Backbone.Model.extend({

  urlRoot: '/api/bears/',

  defaults: function(){
      return{
          task: '',
          description: ''
      }
  },

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

  idAttribute: "_id",
});

Upvotes: 2

Related Questions