为 Azure 移动应用程序在 Azure table 脚本中插入不同的 table

Insert in a different table in Azure table script for Azure Mobile Apps

我一直在广泛搜索这个答案,但只找到了涉及旧 Azure 应用服务而不是新 Azure 移动应用的解决方案。

在这个例子中,在 table 的 Table 脚本中,我将经过身份验证的用户 ID 插入到同一个 table 的 userID 字段中。

table.insert(function (context) {
   context.item.userId = context.user.id;
   return context.execute();
});

但是如果还想将其插入到与用户要求插入的不同 table 中?我如何从 Table 脚本访问另一个 table?

之前,如我发现的所有解决方案所示,您可以 "tables.getTable('otherTable')" 从同一个 SQL 数据库访问另一个 table。但现在我得到一个错误。

阅读 'Azure Mobile Apps - Node SDK' 文档,我发现 "context.tables()" 函数似乎从数据库中获得了不同的 table。但是当我使用下面的代码插入时没有任何反应:

table.insert(function (context) {
    var table2 = context.tables('table2');
    table2.insert({string_column: '1234'});
    return context.execute();
});

谢谢!

找出正确的方法。这是我的代码:

var insertMiddleware = function(req,res,next){

    var table2 = req.azureMobile.tables('table2');
    var toBeInserted = {field1: 'something',
                        id: '1'}; //id is needed 

    var promiseReturned = table2.insert(toBeInserted);
    promiseReturned.then(function(data){
        console.log('Inserted with success!');
        next();
    }, function(error) {
        console.log('Found an error', error);
    });
};

table.insert.use(insertMiddleware, table.operation);

table.insert(function (context) {
   return context.execute();
});

首先,我声明了一个中间件函数,每次调用插入时都会执行该函数。在其中我从我想要访问的 table 调用插入函数,它 returns 是一个承诺。 (那是我的错误)

然后我将中间件与 table 的插入函数相关联,其中脚本是 运行ning 使用 "use" 函数。

终于我运行插入功能正常了。

在我的例子中,我想在生成 id 后将 a 记录插入到另一个 table 中,所以我将其写为回调的一部分。

table.insert(function(context) {
    return context.execute().then(function(results) {
        var table2 = context.tables('table_name');
        var newRecord = {
            id: results.id,
            some: "data",
            more: "123"
        };

        table2.insert(newRecord);

        return results;
    });
});