0

I'm trying to retrieve multiple users from a database, but I'm not sure how to make the query.

I get the IDs from the endpoint like this: localhost:1000/api/user/1,2,3,4 where 1,2,3,4 are the ids of 4 different users.

What I tried to do is to use .split() on the request but I am not able to solve it..

To get all the users I am using this function:

function GetAll(req, res){

    userSchema
        .find({},{_id:0, __v:0})
        .then((data) => res.json(data))
        .catch((error) => res.json({ msg: error }))
};

This is to retrieve a single user:

function GetUser(req, res){
    const { id } = req.params // '1,2,3,4';
    userSchema
        .find({id}, {_id:0, __v:0})
        .then((data) => res.json(data))
        .catch((error) => res.json({msg: error }))
};

I tried to do the split() in GetUser, which only looks for a single user... Is there an easier way to solve it?

I tried something like this:

 function GetUser(req, res){
    const { id } = req.params;
    const idSplited = id.split(",");
    userSchema
        .find({id}, {_id:0, __v:0})
        .then((data)=> data = data.filter((item) => idSplited.includes(item.id)) = res.json(data))
        .catch((error) => res.json({msg: error }))
};
jabaa
  • 5,844
  • 3
  • 9
  • 30
  • Why one endpoint should use two different methods of handling? Why not always expecting a list of ids? – Konrad Jan 29 '23 at 21:40
  • I want to send by url the users id as suggested... `api.com/users?id=id1,id2,id3,id4,id5`, but I don't know how to get all of them in the code... – user20911687 Jan 29 '23 at 22:07
  • The dupe won't help. Sadly, the people you voted to close either didn't understand the problem or didn't read the dupe. It looks like the API works. `id` contains the string `1,2`. The actual problem is the database query. You have to query multiple users. Currently, your code is `find({id: '1,2'}, {_id:0, __v:0})` and the ORM tries to convert `'1,2'` to a number. – jabaa Jan 29 '23 at 22:31
  • Yes, the API works... what I'm trying to do in the code is to `split(",")` the users ids and then show the users... I don't know why the question was closed.... – user20911687 Jan 29 '23 at 22:44
  • That's the reason you should isolate the problem. Your question contains REST API and database query. Your question was closed as a duplicate of a REST API question. The actual problem is in the database query. You should reduce your question to a [mcve], without REST API. I don't see any reason to add this REST API code to this question. – jabaa Jan 29 '23 at 22:44
  • 1
    Flagging as dupe of https://stackoverflow.com/q/32264225/4722345 after the updates. – JBallin Jan 30 '23 at 00:36
  • 1
    Maybe a dupe of https://stackoverflow.com/q/8145523/4722345 instead. – JBallin Jan 30 '23 at 00:41

0 Answers0