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

Incorrect typings being output by rxjs map

combineLatest([of(1), of('test')]).pipe( map(([myNumber, myString]) => { return [myNumber, myString]; }), map(([myNewNumber, myNewString]) => { const test = myNewString.length; }) ); Property 'length' does not ...

I am looking to transfer information from Angular 4 to Java servlet (cross-domain)

Having trouble sending data from Angular 4 to a Java servlet due to access control restrictions. Need to figure out how to properly insert data into the database using the Java servlet. Here is my code snippet: import { Injectable } from '@angular/ ...

What steps should be taken in order to ensure the effectiveness of this keyword search

Currently, I am attempting to implement a keyword search feature for my meteor web app. Although the functionality is there, it's running quite slow. The way it works now is that when a user creates an article, they assign keywords to it. The keyS fun ...

Filtering data in MongoDB using Java to exclude duplicate values

Is there a way to extract data from mongoDB without duplicates? I am looking to refine the following dataset: {"page":"www.abc.com","impressions":1,"position":144} {"page":"www.abc.com","impressions":1,"position":8} {"page":"www.xyz.com","impressions":7," ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

Exclude Cancel button solely from pFileUpload

While using pFileUpload, I am able to see all three buttons, however, I do not require the Cancel button. Even though the documentation mentions an attribute called showCancelButton, applying it does not result in any changes. <p-fileUpload name="demo ...

Ways to conceal result data in case the results are not discovered

I am looking to hide the search results based on the found elements and upon clicking the "x" button, I want to hide the entire results. The back press key is also not responding in my case. Here is a demo: https://stackblitz.com/edit/ionic-1j9sbj?file=p ...

Nested arrays in an Angular interface

As a newcomer to Angular with a background in Java, I am accustomed to setting up classes as data structures for my information. However, after doing some research, I have learned that interfaces should be used instead. I am facing an issue understanding ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Sorting in MongoDB aggregation operations

I have a database containing user activities, and I want to calculate the number of active users and activities they performed each month. The results should be sorted by year first and then by month within each year. Here is my query: query = { ...

Issue with setting cookies using res.cookie

Currently, I am in the process of setting up a Node/Express application with a React client for interaction. I have configured passport to manage authentication using JWT. Upon user login, I verify the email and password, then set the cookie: res.cookie(& ...

What is the best way to combine data from two rows into one row?

Can someone help me with merging 2 sets of Line data into a single row for each entry? For example, the 'Green Bay Packers @ Chicago Bears' row should display '+3.5000 and -3.5000', while 'Atlanta @ Minnesota' should show &apo ...

RxJS Transformation is failing to return the updated object

In my Angular 5.1 single page application, I am encountering an issue with a service response while calling REST services. The problem lies in how the response is handled when it returns an array of Events. Here is how I am trying to transform the response ...

Wondering how to leverage TypeScript, Next-redux-wrapper, and getServerSideProps in your project?

Transitioning from JavaScript to TypeScript for my codebase is proving to be quite challenging. // store.ts import { applyMiddleware, createStore, compose, Store } from "redux"; import createSagaMiddleware, { Task } from "redux-saga"; ...

Angular routerlink params can be secured using encryption and decryption techniques

Can anyone provide me with a reliable method to encrypt and decrypt querystring parameters, such as gmail.com? Also, I am looking for information on how to obtain these query parameters. The path structure I am working with is: { path: 'myPrograms/: ...

A guide on logging errors triggered within reducers

I'm facing a challenge in Redux where I am unable to get error messages logged to the console. My stack includes React, Redux Toolkit, and TypeScript. Here is a snippet of one of the reducers I've implemented: // Reducer const removeResourceRedu ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Tips for creating a Single Xpath instead of Multiple paths

I'm currently working with Protractor alongside TypeScript. I have an element located at: xpath = "**//div[@class='loglist']/div[1]/div[2]**" Afterwards, there are additional elements that need to be identified in different divs s ...

Show the Array List in a left-to-right format

Is there a way to display an array list from left to right with a div scroll, instead of top to bottom? I am having trouble achieving this. Here is my demo code for reference. HTML <div> <h2 class="ylet-primary-500 alignleft">Sessions</h ...