根据路线在MongoDB中删除对象的推荐方法 [英] Recommended way to delete object in MongoDB based on a route

查看:118
本文介绍了根据路线在MongoDB中删除对象的推荐方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MEAN堆栈开发的新手,但是喜欢它!我想以一种不是基于观点的方式提出这个问题,请原谅我.

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.

让我们说我有一个管理仪表板,该仪表板列出了MongoDB集合中的对象.每个项目都有一个具有以下方案的href的删除按钮:href="/admin/ministry/delete/:id"其中:id是要删除的数据库中对象的ID.

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.

现在我有一个路由设置,可以成功地将请求路由到控制器,但是我想知道这是否是删除对象的最佳方法.例如,单击对象的删除按钮后,该对象将被删除,然后返回到仪表板,但是URL仍然是这样的:

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.

路由器

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

控制器

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

    });
}

推荐答案

我建议您使用RESTful API结构.只需看一下API的外观即可:

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

在您的情况下,要删除ministry,用户应向/api/admin/ministry/:id发送DELETE请求.

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

路由器应该是这样的:

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

这篇关于根据路线在MongoDB中删除对象的推荐方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆