0

我有一个如下所示的异步调用链:

getConnections()
  .then(() => addOneNewDoc())
  .then(() => fetchOneDoc());

addNewDoc() 工作正常并插入文档。然后,我使用 API 的查询功能在 fetchOneDoc() 中查询文档。

获取文档的调用总是返回未定义,但我可以在门户数据库浏览器中查看文档。我试过在通话之间睡觉,以防文档在查询之前没有进入,但这也不起作用。

  const query = `select * from items i where i.id = '${docId}'`;

  const {result: doc} = await connection.container.items.query(query);

      if (!doc) {
          console.log('GOT NO DOCS BACK');
      return;
  }

我已经验证了查询在门户中可以正常工作。

4

1 回答 1

0

请参考我的示例代码:

const cosmos = require('@azure/cosmos');
const CosmosClient = cosmos.CosmosClient;

const endpoint = "https://***.documents.azure.com:443/";                 // Add your endpoint
const masterKey = "***";  // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const databaseId = "db";
const containerId = "coll";

async function run() {
    await insertItem(); 
}

async function insertItem(continuationToken) {
    const { container, database } = await init();
    const documentDefinition = { content: 'Hello World!' };

    const { body } = await container.items.create(documentDefinition);
    console.log('Created item with content: ', body.id);
    return await queryItems1(body.id);
}

async function queryItems1(idParam) {
    const { container, database } = await init();
    const querySpec = {
        query: "SELECT r.id,r._ts FROM root r where r.id = '"+ idParam +"'" 
        };
    const queryIterator = await container.items.query(querySpec,null);
    if (queryIterator.hasMoreResults()) {
        const { result: results, headers } = await queryIterator.executeNext();
        console.log(results)
    }   
}
async function init() {
    const { database } = await client.databases.createIfNotExists({ id: databaseId });
    const { container } = await database.containers.createIfNotExists({ id: containerId });
    return { database, container };
}

run().catch(err => {
    console.error(err);
});
于 2018-10-29T09:58:33.870 回答