Using TypeScript in Azure Functions to Make Queries to Cosmos DB

I am a beginner in Typescript and CosmosDB, and I have been searching online all day for a solution to my problem. Unfortunately, I haven't been able to find one that works for my specific case. I hope someone here can help me out.

I have been trying to create RESTful APIs using Azure Functions (JavaScript/Typescript) to connect to and query data from my Azure Cosmos DB. I used data binding to link the database with my functions. However, I'm unsure how to retrieve values from the database based on specific column criteria (e.g., select id from table where username="abc").

For clarification, here is an example of a user item in my Cosmos DB:

{
    "id": "1",
    "userid": "33218898",
    "username": "test1",
    "password": "psw",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bc8dfcc8d9cfc892dfd3d1">[email protected]</a>",
    "momentID": [
        "1",
        "2",
        "3"
    ],
    "followingID": [
        "2",
        "3"
    ],
    "followerID": [
        "2",
        "3"
    ]
}

This is how I fetch users from the Azure Function:

module.exports = async function (context, req, inputDocument) {
    context.log('JavaScript HTTP trigger function processed a request.');
    if (!!inputDocument && inputDocument.length > 0) {
            if(req.query.id || (req.body && req.body.id)){
                context.res = {
                    // status: 200, /* Defaults to 200 */
                    body: "User with id [" + req.query.id + "] is: " + inputDocument[req.query.id-1].username
                };
            }
            else if(req.query.name || (req.body && req.body.name)){
                const user = inputDocument.select("[@username='test1_update']");
                const userid = user.id;
                context.log('User id with username:', userid);
            }else{
                var arr_user = new Array(inputDocument.length);

                for(var _i = 0; _i <inputDocument.length; _i++)
                {
                    arr_user[_i] = inputDocument[_i].username;
                }
                context.res = {
                    status: 200, 
                    body: "Hello " + arr_user
                };
                context.log('Username:', arr_user);
            }
    }  
    else{
        context.log('Nothing in the inputDocument');
    }
};

It seems like the `select` function is not defined in Typescript. Can anyone help me with this issue?

Answer №1

If you're looking to retrieve data from a collection using JavaScript, the @azure/cosmos package can be a helpful tool.

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

getUser: async function (login) {
    const querySpec = {
      query: 'SELECT * FROM users',
      parameters: [
      ]
    };

    const result = await cosmosClient
      .database(databaseId)
      .container(containerId)
      .items.query(querySpec)
      .fetchNext();

    if (result && result.resources) {
      return result.resources[0];
    }

    return undefined;
  }

To see an example of this in action, check out this sample code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble Establishing Connection to Azurite Container from Different Container in Docker with TestContainers .NET Supplied Connection String

Exploring integration tests with TestContainers for .NET, Azurite, and an Azure Function App. Declared Azurite TestContainer: _azuriteContainer = new AzuriteBuilder() .Build(); Azure connection string (in my environment) obtained by calling _azuriteC ...

The element in TS 7023 is implicitly assigned an 'any' type due to the fact that an expression of type 'any' is not valid for indexing in type '{}'

I have implemented a select-box that includes options, labels, optgroups, and values. Is my approach correct or is there something wrong with the way I have defined my types? interface Option { label: string value: string selected?:boolean mainGrou ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

Customize styles for a specific React component in a Typescript project using MaterialUI and JSS

I'm currently exploring how to customize the CSS, formatting, and theme for a specific React component in a Typescript/React/MaterialUI/JSS project. The code snippet below is an example of what I've tried so far, but it seems like the {classes.gr ...

The attribute 'size' is not recognized within the data type 'string[]' (error code ts2339)

When using my Windows machine with VSCode, React/NextJS, and Typescript, a cat unexpectedly hopped onto my laptop. Once the cat left, I encountered a strange issue with my Typescript code which was throwing errors related to array methods. Below is the co ...

Deliver the object to the styled component in Material UI

I have a styled component: import {styled} from '@mui/material/styles'; export const MovieModalStyle = styled(Box)(({theme}) => ({ // ... background: `url(${'https://image.tmdb.org/t/p/w780/' + movie.backdrop_path})`, })); Look ...

Unsteady movement of Three JS OrbitControls during rotation

Currently, I am working on a scene with three.js and using orbit controls to rotate the camera around the scene. Occasionally, while rotating, the camera starts moving erratically before calming down and rotating smoothly again. I have read about orbit co ...

Having trouble setting up Node.js and MongoDB on Windows Azure?

I have been facing challenges while trying to follow the tutorial at . This tutorial helps in creating a simple node.js application with access to a Mongo DB. The issue I keep encountering is when I try to run the program locally using the Start-AzureEmula ...

Steps to execute an Angular directory within a project

Click here for imageWhenever I try to run ng serve command from the directory, it doesn't seem to work and just takes me back to the same directory. I'm having trouble running my Angular project. Any suggestions on how to solve this issue? ...

Sharing information between a cordova plugin and an Angular application

I have been working on an Angular/Cordova app and I am trying to pass the online/offline status to Angular: export class AppComponent implements OnInit { isOff = false; constructor() { document.addEventListener('deviceready', onDeviceRea ...

"Obtain permission from Azure Graph to fetch details for a specific user using their principal

Here is the Node.js code snippet: const GraphkManagementClient = require('azure-graph'); client = new GraphkManagementClient(credentials, tenantId); client.users.get(principalID); The last line triggers an error message: Authorization_Reques ...

Using a for-loop in Typescript to iterate over objects in an array

Consider an Array structured as follows: let bodyDataAnswer = { 'answers':[{ 'question_id':this.verifyCustomer.questions[0].id, 'int_result':this.verifyCustomer.questions[0].answer_template.answers["0"].int_result, ...

I thought enabling CORS would solve the issue, but it seems like the restrictions

This is my setup for an asp.net core web API: public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder ...

When trying to style a Material UI component in Mui v5, no matches for overloads were found

In my attempt to enhance the style of a Material UI Component (TextField) shown in the image, I encountered an error that seems to persist no matter what troubleshooting steps I take. Interestingly enough, I never faced such issues when working with styled ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

What is the reasoning behind not allowing an empty object as the initial value for hooks?

I am encountering an issue with my setProd Hooks. export interface faceProduct { readonly title: string; readonly prodState: string; readonly shipping: string; readonly sold: string; readonly alt: string; readonly material: string; readonly ...

Navigate to the initial error on a form submission in a Reactjs application containing numerous form fields

I am working on a project using React along with Material UI and TypeScript, where I have implemented a form. Upon form submission, if there are validation errors in any input fields, I would like the page to automatically scroll to the first input field w ...

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...