Reputation: 14975
I have a photo model:
var photoSchema = mongoose.Schema({
name: { type: String},
path: { type: String},
vehicle: { type: ObjectId, ref: 'Vehicle' }
});
A photo is deleted with the route:
app.delete('/api/photos/:id/delete', photos.delete (app.get('photos')));
I can delete the photo from mongo using:
exports.deletePhoto = function (dir) {
function (req, res, next) {
var id = req.params.id;
Photos.delete (id, function (err) {
if (err) return next (err);
return res.send ({
status: "200",
responseType: "string",
response: "success"
});
});
};
};
The photo is saved on disk at
app.set('photos', __dirname + '/public/photos');
How do I delete the photo from disk in the deletePhoto function?
Upvotes: 5
Views: 18299
Reputation: 543
You can do as following:
Router
app.delete('/api/photos/:id', photos.deletePhoto);
It follows REST api norms
Exports
exports.deletePhoto = function (req, res) {
Photos.remove({_id: req.params.id}, function(err, photo) {
if(err) {
return res.send({status: "200", response: "fail"});
}
fs.unlink(photo.path, function() {
res.send ({
status: "200",
responseType: "string",
response: "success"
});
});
});
};
Upvotes: 9