在Azure Cosmos存储过程中递归获取文档



我正在尝试为一个简单的wiki生成一个内容树。每个页面都有一个Children属性,用于存储其他wiki页面的id。我正在尝试编写一个SPROC,它可以获取所有文档,然后迭代每个页面的Children属性,并用实际的wiki页面文档替换每个项目。我可以获得第一组文档,但wikiChildQuery返回undefined,我不太清楚为什么。

我已经能够单独使用查询获得文档,但由于某种原因,它在SPROC中不起作用。我这里缺什么了吗?

function GetWikiMetadata(prefix) {
var context = getContext();
var collection = context.getCollection();
var metadataQuery = 'SELECT {"ExternalId": p.ExternalId, "Title": p.Title, "Slug": p.Slug, "Children": p.Children} FROM Pages p'
var metadata = collection.queryDocuments(collection.getSelfLink(), metadataQuery, {}, function (err, documents, options) {
if (err) throw new Error('Error: ', + err.message);
if (!documents || !documents.length) {
throw new Error('Unable to find any documents');
} else {
var response = getContext().getResponse();
for (var i = 0; i < documents.length; i++) {
var children = documents[i]['$1'].Children;
if (children.length) {
for (var j = 0; j < children.length; j++) {
var child = children[j];
children[j] = GetWikiChildren(child);
}
}
}
response.setBody(documents);
}
});
if (!metadata) throw new Error('Unable to get metadata from the server');
function GetWikiChildren(child) {
var wikiChildQuery = metadataQuery + ' WHERE p.ExternalId = "' + child + '"';
var wikiChild = collection.queryDocuments(collection.getSelfLink(), wikiChildQuery, {}, function(err, document, options) {
if (err) throw new Error('Error: ', + err.message);
if (!document) {
throw new Error('Unable to find child Wiki');
} else {
var children = document.Children;
if (children) {
for (var k = 0; k < children.length; k++) {
var child = children[k];
children[k] = GetWikiChildren(child);
}
} else {
return document;
}
}
if (!wikChild) throw new Error('Unable to get child Wiki details');
});
}
}

1.我可以获得第一组文档,但wikiChildQuery返回undefined,我不太确定为什么。

首先,这里应该进行更正。在第一个循环中,您获得了具有documents[i]['$1'].Children的子数组,但是,在GetWikiChildren函数中,您希望获得具有document.Children的子数组?当然是undefined。您需要使用var children = document[0]['$1'].Children;

2.似乎您错过了replaceDocument方法。

您可以参考metaDataQuery函数的代码片段:

for (var i = 0; i < documents.length; i++) {
var children = documents[i]['$1'].Children;
if (children.length) {
for (var j = 0; j < children.length; j++) {
var child = children[j];
children[j] = GetWikiChildren(child);
}
}
documents[i]['$1'].Children = children;
collection.replaceDocument(doc._self,doc,function(err) {
if (err) throw err;
});
}

3.到目前为止,Cosmos db SQL Api不支持部分更新,但它正在进行中。

因此,如果您的sql没有覆盖所有列,则不能用于替换目的。(反馈(需要注意的是,在使用replaceDocument方法时,替换对象中未提及的列将被吞噬。

最新更新