BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

Hello i have an issue with my code here. Initially my crud on chrome does every work i want but then my update query releases some errors i know nothing of. I have googled for about 4 hours now but nothing. Please i need some help.

router.put("/skooliva/student/:id", async (req, res) => {
    const student = {
        fullname: req.body.fullname,
        email: req.body.email,
        mobile: req.body.mobile,
        Date_of_birth: req.body.Date_of_birth,
        ID_number: req.body.ID_number,
        address: req.body.address,
        place_of_birth: req.body.place_of_birth
    }
    
    
    studentPre.findByIdAndUpdate((req.params.id).trim(), { $set: student }, { new: false }, (err,data) => {
        if(!err){
            res.status(200).json({code: 200, message: 'Updated successfully', updateStudent: data})
            // res.send(data);
        }else{
            console.log(err);
        }
    })
})

This is the error i am getting

  messageFormat: undefined,
  stringValue: '"[object Object]"',
  kind: 'ObjectId',
  value: '[object Object]',
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
      at new BSONTypeError (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\bson\lib\error.js:41:28)
      at new ObjectId (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\bson\lib\objectid.js:67:23)
      at castObjectId (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schema\objectid.js:246:12)
      at ObjectId.SchemaType.applySetters (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1201:12)
      at ObjectId.SchemaType._castForQuery (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1648:15)
      at ObjectId.SchemaType.castForQuery (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1636:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1612:20)
      at cast (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\cast.js:347:32)
      at model.Query.Query.cast (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\query.js:5312:12),
  valueType: 'string'
}
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
server running
CastError: Cast to ObjectId failed for value "[object Object]" (type string) at path "_id" for model "studentPre"
    at model.Query.exec (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\query.js:4884:21)
    at model.Query.Query.findOneAndUpdate (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\query.js:3444:8)
    at Function.Model.findOneAndUpdate (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\model.js:2635:13)
    at Function.Model.findByIdAndUpdate (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\model.js:2749:32)
    at C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\routes\index2.js:73:16
    at Layer.handle [as handle_request] (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\express\lib\router\index.js:284:15 {
  messageFormat: undefined,
  stringValue: '"[object Object]"',
  kind: 'ObjectId',
  value: '[object Object]',
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
      at new BSONTypeError (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\bson\lib\error.js:41:28)
      at new ObjectId (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\bson\lib\objectid.js:67:23)
      at castObjectId (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schema\objectid.js:246:12)
      at ObjectId.SchemaType.applySetters (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1201:12)
      at ObjectId.SchemaType._castForQuery (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1648:15)
      at ObjectId.SchemaType.castForQuery (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1636:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\schematype.js:1612:20)
      at cast (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\cast.js:347:32)
      at model.Query.Query.cast (C:\Users\user\OneDrive\Bureau\SKOOLIVA_u\backend\node_modules\mongoose\lib\query.js:5312:12),
  valueType: 'string'
}
connected successfully

What am trying to say is this i am able to create a new user, read and also delete but the update button works only on my browser and when i console log i get the data i updated but simply doesnt display on my db.

1 Like

Hi @Chi_Samuel,

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

Hopefully you’re not experiencing this error still but based off the error, are any of the ObjectId’s invalid in your code? When an invalid ObjectId() is used, this error generally occurs. E.g.:

DB> ObjectId("6348acd2e1a47ca32e79f46f") /// <--- Valid ObjectId
ObjectId("6348acd2e1a47ca32e79f46f") /// <--- No error

DB> ObjectId("6348acd2e1a47ca32e79f46fX") /// <--- Invalid ObjectId
BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

From a quick initial glance, I can see you trim() the req.params.id value, is this to form it into an ObjectId()? I’m not sure where else the issue could occur as they are from the request itself. Perhaps you could print the values (specifically for ObjectId() fields) that are used when you receive this error and verify they are valid ObjectId()'s

Regards,
Jason

2 Likes

thanks for your answer @Jason_Tran! Can you give some examples on how to conveniently check if this ObjectID is valid?
I’m currently checking it like that, but I don’t really like this answer

const getUser = (req, res, id) => {
    try {
        ObjectID(id)
        User
        .findById(id)
        .exec((error, user) => {
            if (error) {
                return res.send(error)
            }
            if (user) {
                return res.json(user)
            } else {
                return res.send(`couldnt find user with id ${id}`)
            }
        })  
    } catch(err) {
        return res.send(`couldnt find user with id ${id}`)
    }
}

Can you give some examples on how to conveniently check if this ObjectID is valid?

Just to clarify, when you state “check if the ObjectID is valid?“, do you mean that the document with a specific ObjectId value exists? Based off your code snippet, I cannot see where an ObjectId validity check is being done. I.e., by “valid” do you mean:

  1. The id value is a valid one
  2. The id value is a valid one and it exists in the collection (those are two separate things)

Additionally, could you advise if you’re getting the same error message as the OP?

I don’t have any specific examples handy but depending on your driver and driver version (I am assuming node in this case but please correct me if I am wrong here), you may wish to use the isValid() method for ObjectId.

Note: docs linked above is for version 4.13 of the Node.JS Driver for MongoDB

Regards,
Jason

1 Like