Home > Software engineering >  MongoDB, BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex charac
MongoDB, BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex charac

Time:05-28

I am doing my projects with no errors, but suddenly server-side crashes and the error is "BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer"

I have tried other suggestions for this similar problem from StackOverflow but it's not working.

I have attached- const ObjectId = require('mongodb').ObjectId;

but not solved yet. The full error of code is

var _this = _super.call(this, message) || this;
                           ^

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
    at new BSONTypeError (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\bson\lib\error.js:41:28)
    at new ObjectId (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\bson\lib\objectid.js:66:23)
    at ObjectId (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\bson\lib\objectid.js:26:20)
    at F:\Web Development\Projects\Fiverr\hridayshaha\server\index.js:107:24
    at Layer.handle [as handle_request] (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\express\lib\router\layer.js:95:5)
    at F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\express\lib\router\index.js:284:15
    at param (F:\Web Development\Projects\Fiverr\hridayshaha\server\node_modules\express\lib\router\index.js:365:14)
[nodemon] app crashed - waiting for file changes before starting...

index.js:107:24 --- console.log(id);

from line 105

        app.get('/events/:id', async(req, res) =>{
        const id = req.params.id;
        console.log(id);
        const query = {_id: ObjectId(id)};
        const items = await eventsCollection.findOne(query);
        res.json(items);

CodePudding user response:

There is no input validation in your code, but you cannot assume that req.params.id always is a valid ObjectId.

You can modify the route path to make sure that the route handler only accepts something that looks like a valid ObjectId:

app.get('/events/:id([0-9a-fA-F]{24})', async (req, res) => { … });

Documented here.

  • Related