0

I'm trying to work on NodeJs req.params method but ending up with this error. See the code first below:

var express = require('express');
require('./db/mongoose');
const User = require('./models/users');
const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());
app.get('/users/:id', (req, res) => {
const _id = req.params.id;
User.findById(_id).then((user) => {
    if (!user) {
        return res.status(404).send();
    }

    res.send(user);
}).catch((e) => {
    console.log(e);
    res.status(500).send();
});
});

After creating a request in the Postman app when I try to run the request, say http://localhost/users/[some random number], it gives me the "Argument passed must be..." error and the Postman gives me a 500 error where it should be giving me 404.

Second, when I enter the ID which is stored in my DB, the code works fine. If there is a problem with ObjectId then the error should occur even when I pass the correct ID but it does not.

Node Js version = 8.11.4
MongoDB version = 4.0.5
Mongoose version = 5.9.18

I'd appreciate if someone could help me out here.

Update: What I've noticed (as pointed out by Vishnu in the answers below) is that when I keep the number of characters same as in any valid ID, does not matter if the program is not able to find the ID, it will work. If I change the number of characters then it shows this problem. So I believe I first need to validate the ObjectId.

So my question is that doesn't Mongoose weed out this problem by automatically converting String IDs into Object IDs?

saadi123
  • 614
  • 1
  • 8
  • 12
  • 1
    Does this answer your question? [Argument passed in must be a single String of 12 bytes](https://stackoverflow.com/questions/26453507/argument-passed-in-must-be-a-single-string-of-12-bytes) or (https://stackoverflow.com/q/30051236/7237613) & read this : https://docs.mongodb.com/manual/reference/method/ObjectId/ – whoami - fakeFaceTrueSoul Jun 17 '20 at 21:37
  • 1
    Yes, that sort of worked. Please see my answer below so that others can benefit as well. Thanks for the help. – saadi123 Jun 18 '20 at 05:19

1 Answers1

1

Looks like User schema is having the _id of type ObjectId and you are passing a random number as _id to the query which mongoose is not able to cast it to an ObjectId. This will through a casting error and the catch statement returns the response with status code 500.

You can use the below function to check if the _id is a valid ObjectId

mongoose.isValidObjectId('some random number')
vishnu
  • 1,961
  • 2
  • 7
  • 11