Cosmos db readDocument API在存储过程中不起作用

时间:2018-09-20 02:31:52

标签: azure azure-cosmosdb

在CosmosDB / DocumentDB中使用readDocument函数的简单存储过程,但是不起作用。

function testRead() {
    var collection = getContext().getCollection();

    var docId =  collection.getSelfLink() + 'docs/myDocId';

    // Query documents and take 1st item.
    var isAccepted = collection.readDocument(docId, {}, function (err, doc, options) {
        if (err) throw err;

        response.setBody(JSON.stringify(doc));
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

它总是显示错误代码400。

  

{“ code”:400,“ body”:“ {\” code \“:\” BadRequest \“,\” message \“:\”消息:   {\\“错误\\”:[\\“执行Java脚本时遇到异常。   异常=错误:创建请求消息时出错\\ r \\ nStack   跟踪:错误:在readDocument上创建请求消息时出错\\ n   (testRead.js:512:17)\\ n在testRead(testRead.js:8:5)\\ n在   __docDbMain(testRead.js:18:5)\\ n位于全局代码(testRead.js:1:2)\\“]} \ r \ nActivityId:   2fb0f7ef-c192-4b56-b8bb-9681c9f8fa6e,请求URI:   / apps / DocDbApp / services / DocDbServer22 / partitions / a4cb4962-38c8-11e6-8106-8cdcd42c33be / replicas / 1p /,   RequestStats:,SDK:   Microsoft.Azure.Documents.Common / 1.22.0.0 \“}”,“ activityId”:“ 2fb0f7ef-c192-4b56-b8bb-9681c9f8fa6e”,“ substatus”:400}

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

根据迈克尔的建议,我的示例现在可以工作了,下面是代码

function testRead() {
    var collection = getContext().getCollection();
    var response = getContext().getResponse();

    var docId =  collection.getAltLink() + '/docs/myDocId';

    // Query documents and take 1st item.
    var isAccepted = collection.readDocument(docId, {}, function (err, doc, options) {
        if (err) throw err;

        response.setBody(JSON.stringify(doc));
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

答案 1 :(得分:0)

您可以试试吗:var docId = collection.getAltLink()+'docs / myDocId'; -自链接不适用于“名称路由”。

答案 2 :(得分:0)

雷德曼。

您可以像这样修改代码:

function testRead() {
    var collection = getContext().getCollection();

    var docId =  collection.getAltLink() + 'docs/myDocId';
    console.log(collection.getSelfLink() + 'docs/myDocId');

    var isAccepted = collection.readDocument(docId, {}, function (err, doc, options) {
        if (err) throw err;

        response.setBody(JSON.stringify(doc));
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

或者您可以使用以下示例代码来查询文档,该文档还包含所有字段。

function testRead() {
    var collection = getContext().getCollection();

    var query =  "select * from c where c.id = '1'";
    var isAccepted = collection.queryDocuments(collection.getSelfLink(), query,function (err, doc, options) {
        if (err) throw err;
        var response = getContext().getResponse();
        response.setBody(JSON.stringify(doc));
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

希望它对您有帮助。