Chris Shaugh Chris Shaugh - 2 months ago 4
Node.js Question

404 when deleting a mongo document via express, mongoose, and angular

I'm new to using the MEAN stack, have learned some of the basics to add data to mongodb using mongoose, express, and ui-router. However, I can't figure out how to delete a document. Whenever I try, I get 404 errors, even though it looks like the link should be correct. Would someone please help? Be kind, my code might be way off...

Here is my angular file:

var app = angular.module('updateTracker', ['ui.router']);

app.factory('courses', ['$http', function($http){
var o = {
courses: []
};

o.getAll = function() {
return $http.get('/courses').success(function(data){
angular.copy(data, o.courses);
});
};

o.create = function(course) {
return $http.post('/courses', course).success(function(data){
o.courses.push(data);
});
};

o.get = function(id) {
return $http.get('/courses/' + id).then(function(res){
return res.data;
});
};

o.addEntry = function(id, entry) {
return $http.post('/courses/' + id + '/entries', entry);
};

o.changeLesson = function(course) {
return $http.put('/courses/' + course._id + '/changeLesson')
.success(function(data){
course.lesson = "New Lesson";
});
};

o.removeCourse = function(course) {
return $http.delete('/courses/' + course._id + '/removeCourse')
.success(function (data, status) {
console.log(data);
});
};

return o;
}]);

app.controller('MainCtrl', [
'$scope',
'courses',
function($scope, courses){
$scope.courses = courses.courses;

$scope.addCourse = function(){
if(!$scope.lesson || $scope.lesson === '') { return; }
courses.create({
lesson: $scope.lesson,
course: $scope.course,
curriculum: $scope.curriculum
});
$scope.lesson = '';
$scope.course = '';
$scope.curriculum = '';
};

$scope.changeLesson = function(course){
courses.changeLesson(course);
};

$scope.removeCourse = function(course) {
courses.removeCourse(course);
};
}]);

app.controller('CoursesCtrl', [
'$scope',
'courses',
'course',
function($scope, courses, course){
$scope.course = course;

$scope.addEntry = function(){
// if($scope.version === '') { return; }
courses.addEntry(course._id, {
version: $scope.version,
notes: $scope.notes,
statusCode: $scope.statusCode,
statusMessage: $scope.statusMessage,
author: 'user'
}).success(function(entry) {
$scope.course.entries.push(entry);
});
$scope.version = '';
$scope.notes = '';
$scope.statusCode = '';
$scope.statusMessage = '';
};
}]);

app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {

$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['courses', function(courses){
return courses.getAll();
}]
}
})
.state('courses', {
url: '/courses/{id}',
templateUrl: '/courses.html',
controller: 'CoursesCtrl',
resolve: {
course: ['$stateParams', 'courses', function($stateParams, courses) {
return courses.get($stateParams.id);
}]
}
});

$urlRouterProvider.otherwise('home')
}]);


My routes:

var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Course = mongoose.model('Course');
var Entry = mongoose.model('Entry');

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

module.exports = router;

router.get('/courses', function(req, res, next) {
Course.find(function(err, courses) {
if(err){ return next(err); }

res.json(courses);
});
});

router.post('/courses', function(req, res, next) {
var course = new Course(req.body);

course.save(function(err, course) {
if(err){return next(err); }

res.json(course);
});
});

router.param('course', function(req, res, next, id) {
var query = Course.findById(id);

query.exec(function (err, course){
if (err) { return next(err); }
if (!course) { return next(new Error('can\'t find course')); }

req.course = course;
return next();
});
});

router.get('/courses/:course', function(req, res, next) {
req.course.populate('entries', function(err, course) {
if (err) { return next(err); }

res.json(course);
});
});

router.post('/courses/:course/entries', function(req, res, next) {
var entry = new Entry(req.body);
entry.course = req.course;

entry.save(function(err, entry){
if(err){ return next(err); }

req.course.entries.push(entry);
req.course.save(function(err, course) {
if(err){ return next(err); }

res.json(entry);
});
});
});

router.put('/courses/:course/changeLesson', function(req, res, next) {
req.course.changeLesson(function(err, course){
if (err) { return next(err); }

res.json(course);
});
});

router.delete('courses/:course', function(req, res) {
Course.remove({
_id : mongodb.ObjectID(req.params.course)
}, function(err) {
if(err) { res.send(err);}
console.log("remove id");
})
});

router.param('entry', function(req, res, next, id) {
var query = Entry.findById(id);

query.exec(function (err, entry){
if (err) { return next(err); }
if (!entry) { return next(new Error('can\'t find entry')); }

req.entry = entry;
return next();
});
});


and my course Schema:

var mongoose = require('mongoose');

var CourseSchema = new mongoose.Schema({
lesson: String,
course: String,
curriculum: String,
entries: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Entry'}]
});

CourseSchema.methods.changeLesson = function(cb) {
this.lesson = "Update Lesson";
this.save(cb);
};

mongoose.model('Course', CourseSchema);

Answer

You forgot to add / in the begining of router.delete and /removeCourse at end as well as did not return value using either res.send or res.json or res.end, etc. This should be like bellow

router.delete('/courses/:course/removeCourse', function(req, res) {
  Course.remove({
    _id : req.params.course
  }, function(err) {
    if(err) { 
      console.log(err);
      res.status(500).send(err);
    } else {
      res.json({});
      console.log("remove id");
   }
  })
});
Comments