Making an API with Node/Express + Mongo.
I'm writing some unit test and I observed if I try to get /profile/1
for _id=1
(I let mongo put the ID by default so I cannot have _id=1
) i got this error
MongooseError: Cast to ObjectId failed for value "1" at path "_id"
I thought I will have an empty object User.
function getProfile(req, res) {
const userId = req.params.userId
User.findById(userId, "-password", (err, user) => {
if (err) {
console.log(err);
res.status(400)
res.json({
success: false,
err
})
res.end()
return
}
if (!user) {
res.status(404)
res.json({
success: false,
message: `Cannot find an User with the userId: ${userId}`
})
res.end()
return
}
res.json({
success: true,
user: user
})
res.end()
return
})
}
My test :
describe('Test /profile route', () => {
it('shouldn\'t find Joe Doe\'s profile with a wrong ID\n', (done) => {
chai.request(server)
.get(`/profile/1`)
.end((err, res) => {
expect(res).to.have.status(404)
done()
})
})
I thought I would have an error 404 (second if, and I know it's not the right code error, just a quick way for me to see where my test goes) but I got a 400 -> meaning an error is return.
I read mongoose documentation and I don't really see ho they explain the return value with the different methods.
The problem is that '1' is not a valid mongoose object id. Therefore it is trying to compare different types.
Try casting it to a object id like so:
userId = mongoose.Types.ObjectId(userId)
and then run your query
User.findById(userId, "-password", (err, user) => { .... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With