Transforming a mongodb operation into an asynchronous function using await and async syntax

After calling the function to retrieve data from MongoDB, an undefined error occurs. It is suspected that converting the function to an async/await function may resolve this issue. However, there is uncertainty on how to make this conversion without disrupting the existing functions and their chains. Is there a straightforward way to switch this to async/await?

studentRoute.route('/read-student/:id').get((req, res) => {
   
    Student.findById(req.params.id, (error, data) => {
      if (error) {
        return next(error)  
      } else {
        res.json(data)
      }
    })
})

The angular front end features the following service:

// Get student
GetStudent(id): Observable<any> {
  let API_URL = `${this.endpoint}/read-student/${id}`;
  return this.http.get(API_URL, { headers: this.headers })
    .pipe(
      map((res: Response) => {
        return res || {}
      }),
      catchError(this.errorMgmt)
    )
}

Within the angular component ts file contract.component.ts:

import { Component, ViewChild, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'; 
import { ApiService } from './../../shared/api.service';
import { Student } from './../../shared/student';
import { Web3Service } from './../../shared/web3.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';

@Component({
  selector: 'app-contract',
  templateUrl: './contract.component.html',
  styleUrls: ['./contract.component.css']
})
export class ContractComponent implements OnInit {
  StudentData: any = [];
  dataSource: MatTableDataSource<Student>;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  displayedColumns: string[] = [
                                 'a',
                                 'b', 
                                 'c', 
                                 'd',
                                 'e',
                                 'f',
                                 'g',
                                 'h',
                                 'i',
                                 'j',
                                 'k',
                                 'l'   
                               ];

  constructor(

    private router: Router,
    private actRoute: ActivatedRoute,
    private studentApi: ApiService

  ) { 
   
      var id = this.actRoute.snapshot.paramMap.get('id');
      this.studentApi.GetStudent(id).subscribe(data => {
        this.StudentData = data;
        this.dataSource = new MatTableDataSource<Student>(this.StudentData);
        setTimeout(() => {
          this.dataSource.paginator = this.paginator;
        }, 0);
      })

  }

  ngOnInit(): void {
  }


}



An undefined error arises in the corresponding contract.component.html file when receiving data from MongoDB using findbyid()

Reference tutorial:

Answer №1

After investigation, it was revealed that the root of the problem was identical to this scenario. When a single item is fetched from the database, it is in object form rather than an array. This object contains attributes with undefined length.

Transforming Object into Array in TypeScript - as *ngFor does not allow iteration over objects

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

Removing fields when extending an interface in TypeScript

Attempting to extend the ISampleB interface and exclude certain values, like in the code snippet below. Not sure if there is an error in this implementation export interface ISampleA extends Omit<ISampleB, 'fieldA' | 'fieldB' | &apos ...

Surprising outcome of map-reduce operation in MongoDB version 3.0

Implementing a map reduce for my website (using MongoDB 3.0, Java 7) has been quite the challenge. In order to test the functionality, I started by running a test but unfortunately, my collection did not reflect any changes from its output: String ma ...

What is the abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...

Is there a way to fetch the latest documents in mongodb-mongoose without relying on the sort method?

In my extensive mongodb collection, each document represents a basic log message that occurs at regular time intervals (e.g. 1 minute). Every time I perform a Find query using Mongoose, the results return the entire database content in the order they wer ...

Error: The port value provided is invalid. Please make sure the port is a number between 0 and 65535. The value received is not a number

Running npm start on Ubuntu 18.04 is causing the following error to occur. Can someone please assist me in resolving this issue? WARNING: Adonis has detected an unhandled promise rejection, which may cause undesired behavior in production. To stop thi ...

The TypeScript extension of a type from an npm package is malfunctioning

I am utilizing the ws package to handle WebSockets in my Node.js project. I aim to include a unique isHealthy attribute to the WebSocket class. The approach I have taken is as follows: // globals.d.ts import "ws" declare module "ws" { ...

Creating a single definition that encompasses the characteristics of both primitive and generic types without the need for combining them

Here is a scenario where I need to consolidate and refactor two types: ... .then((result1: any) => { let promises = { one: $q.when(val1), two: $q.when(val2) }; return $q.all(promises); }) .then((resolvedPromises: any) => { ...

Error: The variable 'err' is undefined in the mongoose mongodb code

Every time I try to execute this code, an error pops up stating that err is undefined Below is the code snippet causing the issue: app.post('/tinder/cards', (req, res) => { const dbCard = req.body; Cards.create(dbCard, (err, data) => { ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

What is the reason for not being able to call abstract protected methods from child classes?

Here is a simplified version of my project requirements: abstract class Parent { protected abstract method(): any; } class Child extends Parent { protected method(): any {} protected other() { let a: Parent = new Child() a.me ...

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

MongoError: Transaction could not be initiated

I recently delved into using mongoose transactions for the first time. Following the guidelines in the documentation and some related articles, I managed to get it up and running with the help of run-rs for local replicas. However, I encountered a couple o ...

¿What is preventing me from merging two arrays within this query handler?

I'm facing an issue while trying to merge arrays from a request with existing arrays in a MongoDB database. Despite my attempts, the arrays do not seem to be merging as expected. Can anyone help me identify what might be causing this problem? router.p ...

Is it necessary to establish a connection to my mongodb database directly within my jest test file, or is it permissible to invoke functions from separate classes that handle the database connection?

Currently in the process of testing my database functions using jest. My javascript file contains a variety of functions that connect to the database, retrieve data, and return an array. The issue I'm facing is when calling these functions from my jes ...

MongoDB aggregation: utilizing the $exists operator to find any existing values

My current challenge involves leveraging MongoDB aggregation for a RESTful api with the following scenario. Let's say I have a Subscriptions model structured like this: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Su ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Implementing TypeScript module resolution with Cucumber-js can be a bit tricky

Currently, I am in the process of creating a Proof of Concept for Cucumber-js using TypeScript. Everything is going smoothly except for one issue - I am facing difficulties when it comes to configuring the module resolution while utilizing tsconfig-paths. ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

Ways to sequentially execute API calls rather than concurrently

Update: Find the complete solution at the end of this answer. Consider the following code snippet: @Injectable() export class FileUploader { constructor(private http: Http) {} upload(url: string, file: File) { let fileReader: FileReader ...

The file node_modules/angular2-qrscanner/angular2-qrscanner.d.ts has been detected as version 4, while version 3 was expected. Resolving symbol

We're encountering a Metadata error that is causing obstacles in our deployment process. This issue is preventing the execution of ng build. Below, you will find the configuration details along with the complete error trace. ERROR in Error: Metadata ...