如何在 $http 调用中指定集合名称?

How to specify a collection name in $http call?

我的 MongoDB 数据库中有多个集合。我有一个 angularJS 应用程序,它必须根据上下文 post 到不同的集合。

如何在 $http 调用中指定集合的​​名称并具有通用的 REST API?

$http 函数:

$http({
    method:"post",
    url:"http://localhost:8080/insertIntoTable",
    headers:"",
    data:"data"
}).success(function(data, status, headers, config) {
    $window.alert('Rest API successful');
}).error(function(data, status, headers, config) {
    $window.alert('Unsuccessful');
});

Post后台方法:

app.post('/insertIntoTable',function(req,res){
    //Establish Connection between client and server
    MongoClient.connect(url,function(err,db){
       //Connection Status Display
       if(err)
           console.log('Error while establishing connection with MongoDB',err);
       else
           console.log('Successfully established connection with MongoDB');
       var collection = db.collection(collectionName);
       collection.insert({ "name": "abc", "email": "xyz" });
       db.close();
       console.log('Connection with MongoDB is terminated');
   })
});

在上面的代码中,我想在 $http 调用中传递变量的值:collectionName。我该怎么做?

Node.js

此方法从 request 查询字符串中读取 属性 并将其用作 table 名称。为防止出现安全问题,还需要对 tableName 进行验证。

// list of valid table names to avoid security issues.
var validTables = ['users', 'customers', 'orders'];
app.post('/insertIntoTable/:tableName', function(req, res) {
   var tableName= req.params.tableName;
   // verify if the table name is a valid table name.
   if (validTables.indexOf(tableName) === -1) {
        res.status(404).send('Not found');       // HTTP status 404: NotFound
        return;               
   }
   // use tableName as collection name. 
}

在AngularJs

在客户端,将 table 名称作为常规路径发送,即发出请求,如下例所示:

$http({
    method:"post",
    url:"http://localhost:8080/insertIntoTable/users", // note "users"
    data:"data"
}).success(function(data, status, headers, config) {
    // process success
}).error(function(data, status, headers, config) {
    // process error
});