我有一个Azure函数,该函数查询CosmosDB以获取其包含在集合中的文档:
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (context.bindings) {
var doc = context.bindings.inputDocument;
context.log('Get ready');
context.res = {status: 200, body: doc};
context.log(context.res);
}
else {
context.res = {
status: 400,
body: "Something went wrong"
};
}
context.done();
};
此查询将带回所有内容,而我只是在寻找要返回的特定项目。我如何重构它以仅拉回某些元素?我已经尝试过使用以下方法:
doc.id
这是配置为cosmosdb的sql api的json结构:
{
"id": "1",
"drink": "gin_and_tonic",
"ingredients": [
"2 ounces gin",
"2 lime wedges",
"3–4 ounces tonic water"
],
"directions": "Add gin to a highball glass filled with ice. Squeeze in
lime wedges to taste, then add them to glass. Add tonic water; stir to
combine.",
"glass": [
"highball",
"hurricane"
],
"image": "https://images.unsplash.com/photo-1523905491727-d82018a34d75?
ixlib=rb-
0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=52731e6d008be93fda7f5af1145eac12&auto=fo
rmat&fit=crop&w=750&q=80"
}
代替doc,但这不返回任何内容。我也在尝试使用@ azure / cosmos npm模块,但似乎有点过大,而且似乎没有直接使用函数中定义的输入。有什么想法吗?
答案 0 :(得分:0)
var doc = context.bindings.inputDocument;
输入绑定是一个文档数组,即使只有一个文档也是如此。这就是doc.id
不返回任何内容的原因。
两种解决方案:
根据您的尝试进行过滤。
var doc = context.bindings.inputDocument;
var idArray = [];
for (var i = 0; i < doc.length; i++) {
idArray.push(doc[i].id);
}
context.log('Get ready');
context.res = {status: 200, body: idArray};
context.log(context.res);
查询中的过滤器。转到function.json
,在cosmosdb绑定中,像这样添加"sqlQuery": "SELECT c.id FROM c"
{
"name": "inputDocument",
"type": "cosmosDB",
"direction": "in",
"databaseName": "DBNAME",
"collectionName": "COLLECTIONNAME",
"connectionStringSetting": "CosmosDBConnectionString",
"sqlQuery": "SELECT c.id FROM c"
}
,您可以使用原始代码context.res = {status: 200, body: doc};
来获取所需的商品。