Duplicate items within an array were found when receiving Node.js response data in Angular

I'm facing an issue where duplicate elements are being displayed in an Angular table when receiving data from Node.js. The array sent by Node.js contains 2 elements, but somehow it appears as 4 elements in the Angular table. This discrepancy is puzzling as both consoles in Node and Angular show the correct array length. Here's a snippet of the console log:

Angular Component ts file method

onGetRequisitionToEdit(id){
    this.requisitionService.getRequisition(id)
      .subscribe(resData => {
        console.log('resData.shortlist.length', resData.shortlist.length);
        console.log('resData.shortlist', resData.shortlist);
        // pls see screenshot of console
        this.requisition = resData.requisition;
      
        // more code
    })

Angular Service method

  getRequisition(id: string) {
    return this.httpClient.get<{requisition: Requisition, interviews: Interview[], shortlist: Shortlist[], history: Syslog[]}>(this.reqUrl + '/get/' + id);
  }

Node controller method

exports.getRequisition = (req, res, next) => {
  requisitionService.getRequisition(req.params.id)
    .then(resData => {
      res.status(200).json(resData);
    })
    .catch(err => {
      res.status(500).json({
        message: "Server Error in fetching requisitions: " + err
      });
    });
}

Node Controller Service

async function getRequisition(id){
  const requisition = await Requisition.findById(id);
  if(!requisition) {
    throw 'Requisition not found';
  }

  let interviews;
  interviews = await Interview.find({reqnId: id}).collation({ locale: 'en'});
  if(!interviews) interviews = [];

  let shortlist;
  shortlist = await Shortlist.find({reqnId: id}).collation({ locale: 'en'});
  if(!shortlist) shortlist = [];
  console.log('shortlist', shortlist);
  ///////////// output: 2 elements

  let history;
  history = await Syslog.find({reqnId: id}).collation({ locale: 'en'});
  if(!history) history = [];

  const resData = {
    requisition: requisition,
    interviews: interviews,
    shortlist: shortlist,
    history: history
  }

  return resData;
}

Please assist me in identifying where I might be making a mistake.

https://i.stack.imgur.com/gz6bg.png

Answer №1

If it's feasible, I suggest differentiating the items in the backend. If not, you can employ the filter() function, a versatile JavaScript function that is also compatible with Typescript.

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

I possess legacy Angular 1 code in which I implemented div styles. How can I replicate the same functionality in Angular 11?

Recently, I have been revamping an older project and encountered a challenge in setting the style of an array where each point needs to have a unique position. The Divs are all identified by id = obj.id, and I must assign specific left and top values to ea ...

The best practices for handling assets (css) in MEAN.js and Node.js

MEAN.js utilizes configuration files for managing CSS files, as well as automatically loading all CSS files for each module. Query #1: What is the method to exclude specific files from the list? Query #2: How can a particular CSS file be included only on ...

Best practices for effectively managing errors within JSON web tokens

I am a novice attempting to manage JWT verification. Within the function below, my goal is for the system to generate a new access token based on the refresh token if the user's access token has expired. import { asyncHandler } from "../utils/asy ...

What could be causing the multer middleware to fail to work properly?

Within the app.js file, there is a direct route to handle image uploads: app.post('/upload', upload.single('image'), (req, res) => { res.json({ message: 'pic uploaded' }); }); Posting to /upload successfully uploads the im ...

Decode the JSON serialized format generated by CircularJSON

I have a JSON object in my node.js code that contains circular references. To send this information to the browser, I utilized the NPM package circular-json to stringify the object and serialize the circular references: var CircularJSON = require("circula ...

What is the best way to ensure observables in a template (using async pipe) are fully subscribed to before executing any initialization code?

I am facing an issue with my HTTP service that returns information based on a given item ID. The data is fetched using a Subject, which receives the initial data in the ngOnInit method. To display the returned data in the HTML, I utilize the async pipe. ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

The installation of the executable in npm is set to be in usr/local/share/npm/bin instead of usr/local

After attempting to globally install npm serve, I encountered an issue when trying to run the serve executable. $ npm install -g serve Despite a seemingly successful installation, it appears that the serve command could not be found. It was discovered th ...

Using the digitallyseamless/nodejs-bower-grunt docker image to containerize npm and bower installations

I've been exploring the possibilities of using Docker to execute npm and bower install commands. Below is my setup: ./package.json { "name": "bignibou-client", "version": "0.1.0", "engines": { "node": "0.10.x" }, "devDependencies": { ...

Is there a way to link node.js with mongodb?

Looking to establish a connection between my node.js and MongoDB. --> Currently running MongoDB version 6.5.0 (installed as a service with complete setup) --> Installed mongosh (MongoDB terminal) for database access and modifications --> Successfu ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

"The loop functionality appears to be malfunctioning within the context of a node

Below is the code snippet: for (var j in albums){ var album_images = albums[j].images var l = album_images.length for ( var i = 0; i < l; i++ ) { var image = album_images[i] Like.findOne({imageID : image._id, userIDs:user ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Optimal strategies for managing subscriptions in Angular

I'm currently pondering about the concept of angular subscription and unsubscription. The amount of information available on this topic is overwhelming, making it hard for me to navigate through. When is the right time to unsubscribe from a subscript ...

Originator of event within the NodeJS EventEmitter

When dealing with a NodeJS app that forks multiple child processes, it becomes important to identify which child process has exited. However, the callback function triggered by the EventEmitter does not provide information about the sender of the event. H ...

The Swagger-ui tool condenses objects into query parameters, while the angular client that it generates does not

I'm currently working on a Spring Boot application that includes the following Rest function: @SecuredMaster @GetMapping(path = "/mitarbeiter") @Operation(security = {@SecurityRequirement(name = "jwt")}) public Page<MitarbeiterListRow> getMitar ...

Simplifying imports in Angular, the easy way: A guide to stream

We recently made a change to our Angular project by moving the npm-library @ng-plus/modal to live as a project library under the project/ngplus-modal folder. One issue we encountered is with the imports within the project. Even though we previously def ...

Verifying User Permissions with Angular 2/4 and API

I am currently in the process of developing an Angular 2/4 application that interacts with an API built in Laravel 5.4. One area I'm seeking guidance on involves checking authentication and permissions on the backend through Angular. I want to verify ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

Is there a way to update all scoped packages to a specific tagged version at once?

Is there a method to upgrade all scoped packages to a specific tag other than latest? For example, let's say I have multiple packages under the scope @scope, such as @scope/pkg1, @scope/pkg2, and so on. These packages have tags like stable. Is it pos ...