0

I am getting stuck on the delete method for my API. My application requires a user to log in and then he can add courses. The courses are stored in a nested array inside the User model. I want the user to be able to cancel (delete) a course from the view and then have the course deleted from the user's profile on the server. I am getting a 404 response event though the variables I am comparing are identical.

This is my ajax call to delete a specific course:

jQuery.ajax({
    url: "/test/signups/5387c1a0fb06e48f4658170c", 
    type: "DELETE",

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

This is my delete method:

app.delete('/test/signups/:id', isLoggedIn, function(req, res) {
    User.findOne({'_id': req.user.id }, function(err, user) {
        if (err)
           return done(err);

    if (user) {
        var found = false;
        var singlesignup = user.signup.filter(function(e){ return e._id == req.params.id })[0]

        user.signup.forEach(function (singlesignup, index) {
            if (singlesignup._id === req.params.id) {
                found = index;
            }
        });

        if(found) {
            user.signup.splice(found, 1);
            res.json(200, {status: 'deleted'});
        } else {
            res.json(404, {status: 'invalid survey question deletion'});
        }
    }       
   });
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sizzles27
  • 94
  • 12

1 Answers1

1

The _id values in mongodb are not strings, they are instances of the ObjectId class and they don't work correctly with the == or === operators. It's completely a nuisance. But anyway try converting them to strings before comparing: singlesignup._id.toString() === req.params.id. To get it truly correct in the long run, make sure you handle all the cases of null, string or ObjectId. Consider a helper library such as objectid.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274