Recommended way to delete object in MongoDB based on a route

ぐ巨炮叔叔 提交于 2019-12-24 03:38:08

问题


New to the MEAN stack development, but loving it! I want to ask this question in such a way that it isn't opinion based, so forgive me if it is.

Lets say I have an admin dashboard that lists out the objects in a MongoDB collection. Each item has a delete button that has a href of this scheme: href="/admin/ministry/delete/:id" where :id is the id of the object in the DB to delete.

Right now I have a route setup that successfully routes the request to the controller, but I'm wondering if this is the best way to delete an object. For example, once I click on the delete button for an object, it gets deleted and we are back to the dashboard, but then the URL remains something like this: http://localhost:3000/admin/ministry/delete/554b88546d280ab11603b062

So essentially my question is, what suggestions would you have for my route and controller when it comes to deleting an object from the DB.

Router

var admin_ministry_controller = require('./controllers/admin/ministry_controller.js');
app.get('/admin/ministry/delete/:id', ministry_controller.delete);

Controller

var mongoose = require('mongoose');
var Ministry = mongoose.model("Ministry");

exports.delete = function(req, res) {
    Ministry.findOne({_id:req.params.id}).exec(function(err, ministry){
        if(ministry) {
           ministry.remove();
        }

        var query = Ministry.find();
        query.exec(function(err, doc) {
            res.render('admin/ministry', {title: 'Next Steps | Ministry', msg: "Deleted Ministry", ministries: doc});
        });

    });
}

回答1:


I would suggest you to use RESTful API structure. Just take a look at what the API will look like:

In your case, to delete ministry, users should send a DELETE request to /api/admin/ministry/:id.

And the router should be like this:

app.delete('/admin/ministry/:id', ministry_controller.delete);


来源:https://stackoverflow.com/questions/30169944/recommended-way-to-delete-object-in-mongodb-based-on-a-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!