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 }))
};
7
  • Why one endpoint should use two different methods of handling? Why not always expecting a list of ids? Commented Jan 29, 2023 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... Commented Jan 29, 2023 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. Commented Jan 29, 2023 at 22:31
  • 1
    Flagging as dupe of stackoverflow.com/q/32264225/4722345 after the updates. Commented Jan 30, 2023 at 0:36
  • 1
    Maybe a dupe of stackoverflow.com/q/8145523/4722345 instead. Commented Jan 30, 2023 at 0:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.