Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids.

Here's a snippet from the Angular component code:

this.orderService.getSpecyficOrders(ids)
    .subscribe(orders => { ... 

Where ids is an array of

[{_id : ID },{_id : ID },{_id : ID },]

The ID is a string in the format "5235sd23424asd234223sf44" taken from MongoDB documents.

In the Angular service file, I have imported: Http, Headers, and import 'rxjs/add/operator/map';

Below is the code in the Angular service:

getSpecyficOrders(ids){
    return this.http.get('/api/ordersspecyfic', ids)
        .map(res => res.json());
}

In the Express file, I have required: multer, express, router, mongojs, db

And here is part of the code in Express for calling to MongoDB:

router.get('/ordersspecyfic', function(req, res, next){
    var ids = req.body;
    ids = ids.map(function (obj){ return mongojs.ObjectId(obj._id)});
    db.orders.find({_id: {$in: ids}}, function(err, orders){
        if(err){
            res.send(err);
        }
        res.json(orders);
    });
});

However, I'm encountering an error:

Uncaught Response {_body: "TypeError: ids.map is not a function
  &n…/node_modules/express/lib/router/index.js:46:12)↵", status: 500, ok: false, statusText: "Internal Server Error", headers: Headers…}

When logging req.body in the Express file, it shows me that it is an empty object {}

I understand that req.body is not an array by default, but I'm unsure if that's the only issue with the code.

All other requests like getting a single element or all items are working fine. I just can't seem to get this one to work properly.

Answer №1

If you are attempting to send ids to your server-side using the following code:

return this.http.get('/api/ordersspecyfic', ids)

please note that the http.get method does not function in that manner.

The correct syntax for get() is get(url: string, options?: RequestOptionsArgs) : Observable

To transmit this data to your backend, you should utilize the post method instead.

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post('/api/ordersspecyfic', ids, options)

The proper usage of post() is post(url: string, body: any, options?: RequestOptionsArgs) : Observable

For more information, refer to:https://angular.io/docs/ts/latest/api/http/index/Http-class.html

Answer №2

There are two errors to address, one in the backend and one in the frontend.

  1. Frontend Mistake

The error lies in your code snippet

this.http.get('/api/ordersspecific', ids);
. This call only attempts to fetch data from /api/ordersspecific without sending any specific ids. Your second parameter does not correspond to any RequestOptions, causing your ids to be overlooked.

To include ids in the request, you should append them as a query string. Learn how to add querystring parameters here. In essence, it can be accomplished like this:

return this.http.get('/api/ordersspecyfic?ids=<id1>&ids=<id2>...'
  1. Backend Issue

In the backend logic, you're attempting to read data from the body of a GET request. There should not be any payload in a GET request, so you should retrieve this information from the query string instead:

router.get('/ordersspecyfic', function(req, res, next){
  var ids = req.query.ids;
});

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

When transmitting data from the Backend in JSON format, the Frontend is displaying the data as text/html instead

I have successfully built the backend using NodeJS and the frontend using ReactJS. However, I encountered an issue where when accessing data from Postman, it is in JSON format, but when fetching the data on the frontend, the API returns HTML/text data inst ...

Encountering a TypeScript error in MUI 5 when attempting to spread values in props

I am encountering an issue with a typescript error related to the MUI sx prop. The problem arises when I attempt to merge or spread multiple sx values into an sx prop, resulting in an error. It seems to work fine if only one item is present in the sx prop, ...

Attempting to retrieve JSON data and present it in a grid layout

I have a JSON file with the following data: { "rooms":[ { "id": "1", "name": "living", "Description": "The living room", "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz7 ...

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...

Formatting the string value

Having trouble formatting the input value. Take a look at this code snippet: <input type="text" class="form-control" name="time" formControlName="time" (input)="convertToMinute($event.target.value)" /> Here is the function in question: ...

Troubleshooting a Node/Express RESTful API using node-inspector for debugging

Among the various questions I've come across regarding debugging a Node/Express application, most seem to pertain to a node web application rather than a RESTful server. In my case, I have successfully developed a simple server that operates flawless ...

Using CamanJs in conjunction with Angular 6

Struggling to integrate camanjs with Angular 6? Wondering how to add the JavaScript library and use it within an Angular project when there are no types available on npm? Here are the steps I followed: First, install Caman using npm. Next, add it to ...

Exploring the money library in typescript after successfully installing it on my local machine

I've been struggling to set up a new library in my TypeScript project for the first time, and I can't seem to get it functioning properly. The library in question is money. I have downloaded it and placed it in the root of my project as instructe ...

When working with TypeScript, it's important to note that an implicit 'any' type may occur when trying to use an expression of type 'string' to index a specific type

Currently, I'm attempting to transfer a custom hook used in Vue for handling i18n from JavaScript to TypeScript. However, I am encountering a persistent error message: An element is implicitly assigned the type 'any' due to an expression o ...

Should we implement REST API with authentication?

I am seeking guidance on building an application from scratch and I have encountered some challenges. The plan is to create a front-end using Angular and a backend that will communicate via REST API. This application will be deployed on individual devices, ...

Struggling with breaking down passport.js into modules in node.js

Hey there, I'm facing a bit of an issue with my login route: var express = require('express'); var router = express.Router(); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; re ...

Navigating to views in Express using Jade templates

When I try to path to a view located in the ./views directory, Express is able to render it successfully. However, when I attempt to render a view such as ./views/api/login.jade, I encounter an issue where it sends back a 500: Internal Server Error. Here ...

Guide to initiating an Angular 6 project using Angular CLI version 7.3.3

My current Angular CLI version is 7.7.3, but I need to create an Angular 6 project using it. When I use the CLI command 'ng new project_name', it only allows me to create an Angular 7 project. Is there a way to force creating an Angular 6 project ...

Derive data type details from a string using template literals

Can a specific type be constructed directly from the provided string? I am interested in creating a type similar to the example below: type MyConfig<T> = { elements: T[]; onUpdate: (modified: GeneratedType<T>) => void; } const configur ...

"Utilize Node.js to add a new entry to Redis database by incorporating a

I am encountering an issue with posting/inserting data into my redis database using the POST method. I am using express js as a framework and here is the code snippet: app.post('/create/:id', function (req, res) { return client.set(req.params. ...

Sharing Data Across Multiple Windows in Angular 2 Using a Singleton List

My multiplayer game involves adding new players to a single game room lobby, which is essentially a list of current players. How can I update this list for all connected players when new ones join? I implemented a service and included it in the providers ...

Issue with Angular 8: Unable to access property 'database' of undefined when using @firebase

Recently, I decided to upgrade my configuration from angularfire2 v4 to @angular/fire v5.2.1 and firebase from v4 to v6.2.4. Unfortunately, during this process, I encountered an issue that caused the console to log the following error message: TypeError: ...

Tips for ensuring a successful POST request using a hyperlink tag

Within my view file, I have the following code snippet: <a href="/logout" role="button" class="btn btn-lg btn-primary left-button">Logout</a> Inside my app.js file, I have implemented the following route for loggi ...

Service consuming in Angular 2 using Stomp protocol

Why am I seeing responseBody as undefined, but I am able to see the subscribe response in msg_body? What could be causing this issue with responseBody? let stomp_subscription = this._stompService.subscribe('/topic/queue'); stomp_subscription.ma ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...