【问题标题】:Azure Serverless Insert data into Cosmos dB using javascriptAzure Serverless 使用 javascript 将数据插入 Cosmos dB
【发布时间】:2019-11-08 00:00:55
【问题描述】:

所有,我正在尝试查找一些文档,以使用我的无服务器函数将数据插入 Cosmos DB 集合。我正在使用 httptriggers 从请求中获取数据并将其插入到 cosmos 中。

我找不到任何关于此的文档.. 尤其是使用 javascript。

这是我现在所拥有的,但它会引发错误。
我的 Index.js 文件

module.exports = async function (context, req) {
    const endpoint = "https://localhost:8081/";
    const key = "key here";
    const database = "NodeSamples";
    const container = "Data";
    const itemDefs = JSON.parse({"fname":"John","lname":"Doe"});
    await Promise.all(itemDefs.map((itemDef: any) => container.items.create(itemDef)));
};

任何帮助将不胜感激

【问题讨论】:

  • 你能告诉我什么是“你的无服务器功能”吗?你用的是 Azure Function 吗?

标签: javascript node.js azure azure-cosmosdb serverless


【解决方案1】:

你可以从here找到文档,你需要导入必要的包

module.exports = async function (context, req) {

    // We need both name and task parameters.
    if (req.query.name && req.query.task) {

        // Set the output binding data from the query object.
        context.bindings.taskDocument = req.query;

        // Success.
        context.res = {
            status: 200
        };
    }
    else {
        context.res = {
            status: 400,
            body: "The query options 'name' and 'task' are required."
        };
    }
};

【讨论】:

【解决方案2】:

如果您想要在 Azure Functions 中使用 Cosmos DB SDK,您可以:

使用 Cosmos DB JS SDK

包裹:https://github.com/Azure/azure-cosmos-js/

参考:https://docs.microsoft.com/azure/azure-functions/manage-connections#cosmosclient-code-example-javascript

const cosmos = require('@azure/cosmos');
const endpoint = process.env.COSMOS_API_URL;
const key = process.env.COSMOS_API_KEY;
const { CosmosClient } = cosmos;

const client = new CosmosClient({ endpoint, key });
const container = client.database("MyDatabaseName").container("MyContainerName");

module.exports = async function (context) {
    const itemDefs = JSON.parse('[{"id":"SomeId", "fname":"John","lname":"Doe"}]');
    await Promise.all(itemDefs.map((itemDef: any) => container.items.create(itemDef)));
}

使用 Cosmos DB 函数绑定

绑定是与 Cosmos DB 交互的一种简单方法,因为它们涵盖了基本场景,而无需执行诸如维护单例客户端实例之类的事情,但如果您想做很多事情(查询文档、保存文档、更新等) ) 在相同的函数执行上,那么您最好的选择是使用第一个选项。

参考:https://docs.microsoft.com/azure/azure-functions/functions-bindings-cosmosdb-v2#output---javascript-examples

module.exports = function (context) {
  const itemDefs = JSON.parse('[{"id":"SomeId", "fname":"John","lname":"Doe"}]');
  context.bindings.documentsToSave = itemDefs;
  context.done();
};

已经用绑定定义了你的function.json

{
    "name": "documentsToSave",
    "type": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connectionStringSetting": "MyAccount_COSMOSDB",
    "direction": "out"
}

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多