I'm running a node.js console app from the official tutorial in the azure documentation. Please find the link below: https://docs.microsoft.com/en-us/azure/cosmos-db/sql/sql-api-nodejs-get-started The code is below:
const cosmos = require("@azure/cosmos");
const CosmosClient = cosmos.CosmosClient;
const endpoint = "******"; // Add your endpoint
const masterKey = "******"; // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const databaseId = "brondbid"; // Add the Database ID
const containerId = "broncollectid"; // Add the Container ID
const querySpec = {
query: "SELECT * FROM c"
};
async function run() {
const { result: results } = await client.database(databaseId).container(containerId).items.query(querySpec, { enableCrossPartitionQuery: true }).toArray();
for (var queryResult of results) {
let resultString = JSON.stringify(queryResult);
console.log(`\tQuery returned ${resultString}\n`);
}
}
async function handleError(error) {
console.log("\nAn error with code '" error.code "' has occurred:");
console.log("\t" error.body || error);
}
run().catch(handleError);
When I'm running node app.js at the terminal, I'm getting this error.
An error with code 'undefined' has occurred:
undefined
CodePudding user response:
Please try this code:
const cosmos = require("@azure/cosmos");
const CosmosClient = cosmos.CosmosClient;
const endpoint = "******"; // Add your endpoint
const masterKey = "******"; // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, key: masterKey });
const databaseId = "brondbid"; // Add the Database ID
const containerId = "broncollectid"; // Add the Container ID
const querySpec = {
query: "SELECT * FROM c"
};
async function run() {
const database = client.database(databaseId);
const container = database.container(containerId);
const { resources: results } = await container.items.query(querySpec, { enableCrossPartitionQuery: true }).fetchAll();
for (var queryResult of results) {
let resultString = JSON.stringify(queryResult);
console.log(`\tQuery returned ${resultString}\n`);
}
}
function handleError(error) {
console.log(error);
console.log("\nAn error with code '" error.code "' has occurred:");
console.log("\t" error.body || error);
}
run().catch(handleError);
Essentially your code was failing because there is no .toArray()
method available on the query result. Since it is not a REST API error, you are getting the undefined
for error code.
Also, the query returns the data in resources
key and not result
key like you are using.