【问题标题】:How to send a request from express to mongodb to delete multiple record from collections如何从 express 向 mongodb 发送请求以从集合中删除多条记录
【发布时间】:2018-01-27 17:07:49
【问题描述】:

使用 angular 和 express 从 mongodb 集合中删除多条记录。

如何将 id 数组从 express 发送到 mongodb。

这是在 express 中从 mongodb 中删除单个 todo 的代码

 app.delete('/api/todos/:id', function(req,res){
        Todos.remove({
            _id: req.params.id
        }, function(err, todos){
            if(err)
                res.send(err);
            Todos.find(function(err, todos){
                if(err)
                    res.send(err)
                res.json(todos);
            });
        });
    });

角度控制器代码

$scope.deleteTodo = function(id){
    $http.delete('/api/todos/'+ id).then(function(response){
        var data = response.data;
        $scope.todos = data;
    });
}

【问题讨论】:

    标签: angularjs node.js mongodb express mongoose


    【解决方案1】:

    简单的方法是通过传递逗号分隔的 ID 列表来重复使用您的路线,例如/api/todos/id1,id2,id3.

    app.delete('/api/todos/:ids', function (req, res) {
        Todos.remove({
            // convert string of IDs to array of IDs
            _id: { $in: req.params.ids.split(',') }
        }, function (err) {
            if (err) return res.send(err);
            Todos.find({}, function (err, todos) {
                if (err) return res.send(err)
                res.json(todos);
            });
        });
    });
    

    【讨论】:

    • 它适用于静态 id,如何通过将 id 数组从角度控制器传递到中间件快速控制器来实现
    【解决方案2】:

    如何将 id 数组从 express 发送到 mongodb。

    在这个示例中,我将向您展示如何从参数创建一个数组,并使用下划线在每个循环中遍历 id 数组以逐个删除。

    app.delete('/api/todos/:id', function(req,res){
      try{ //:id can be a list of ids separated by ','
       var deleteID = req.params.id.split(','); //array is made
       // Temp. Error Log
       var errorCount = 0; var errorLog = '[ERROR LOG]\n';
       // Delete each ID
       _.each(deleteID,function(this_id,index){
         Todos.remove({id:this_id},function(err,todos){
          //errors occuring while deleting, stored into temp log
          if(err){errorCount++;errorLog+="\n["+index+"]\n"+err;}
         });
       });
       // Check if any errors happened
       if(errorCount!=0){ // RETURN ERRORS :
        res.send(errorLog);
       }else{ // NO ERRORS :
        Todos.find(function(err, todos){
         if(err){res.send(err);}
         else{res.json(todos);}
        });
       }
      }catch(e){res.end(); console.log(e);}
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 2018-10-31
      • 2014-02-10
      • 2018-11-12
      • 2016-12-27
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      相关资源
      最近更新 更多