Error: Cast to ObjectId failed for value \"batchquery\" (type string) at path \"_id\" for model \"Users\"

I’m getting this error in my API using NodeJS, Express, and MongoDB when doing a batch query (GET). I am able to POST, PUT, and DELETE multiple documents by _id but for some reason I get this error when doing this query:

GET: http://localhost:3001/users/batchquery?userIds=649627038375fa0beb5d8102,6496209b9fa3f73cf1885dfa,648e8afe2ad965a4222f5afe

Here is my API:

//Use batch object to retrieve multiple objects in one operation
app.get('/users/batchquery', passport.authenticate('jwt', { session: false }), async (req, res) => {
  const { userIds } = req.query;

  try {
    // Split the userIds into an array
    const ids = userIds.split(',');

    // Perform the query using the $in operator to fetch multiple users at once
    const users = await Users.find({ _id: { $in: ids } });

    // Send the response with the retrieved users
  } catch (error) {
    // Handle errors
    res.status(500).json({ error: 'An error occurred' });

Have been at this for hours and so far have not found any fix online. Would appreciate any advice :slight_smile: Thanks!

1 Like

Found the fix (hope this helps someone else :slight_smile: )

The route /users/batchquery was conflicting with the route parameter /users/:userId that handles individual user retrieval.

What I did was modified the order of the route handlers so that the /users/batchquery route is defined before the /users/:userId rout-- and it worked! :slight_smile: :star_struck:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.