MFaiqKhan
MFaiqKhan

Reputation: 83

CastError: Cast to ObjectId failed for value "0" (type string) at path "_id" for model "Users", in findOne and others

I am fairly new to mongodb and nodejs. I am getting an error by when I try to get specific user by req.params.id from database.

app.get('/user/:id', (req,res) => {
    console.log(req.params.id)
    Users.findOne({_id: req.params.id}, (err,user) => { 
        if(!err) {                                      
            res.send(user)                           
            console.log(user);
        } else {
            console.log(err);
            res.status(500).send('Error Happened')
        }
    })
})

in mongodb atlas I am getting { _id : (hexstring) name : email:
address: __v: }

. Every line or block of code containing req.params.id is giving errors, while Users.save() is working and .remove() is also working fine and I think .find() is also working fine

Upvotes: 0

Views: 427

Answers (1)

Parzh from Ukraine
Parzh from Ukraine

Reputation: 9913

In MongoDB, ObjectId has a strict requirement of being a 12-byte string.

"1" is not a valid ObjectId.

Upvotes: 1

Related Questions