saadi123
saadi123

Reputation: 614

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters with wrong ID

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?

Upvotes: 0

Views: 612

Answers (1)

vishnu
vishnu

Reputation: 2011

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')

Upvotes: 1

Related Questions