Tags

, ,

If ever you’ve encounter an error that says ”
TypeError: hex is not a function
at Function.from (native)
at Function.from (native)
at new ObjectID (C:\MyblogApp\node_modules\mongodb\node_modules\mongodb-core\node_modules\bson\lib\bson\objectid.js:52:32)
at C:\MyblogApp\models\mongodb\blogs.js:478:26″

And in your Line 478(blogs.js), you use the ObjectId method.
var ObjectId = require(‘mongodb’).ObjectID;
var docId = new ObjectId(id);
Blogs.findOne({‘_id’:docId}).exec()…

It seems you’re using a wrong version of mongodb!!

To fix the problem.. two(2) solutions that you can choose.
Solution A:
Uninstall the recent mongodb version and use the older version
So I run a command npm list –depth=0 to check the mongodb and mongoose version.
Here’s the report:
├── mongodb@2.2.16
├── mongoose@4.7.2

$ npm uninstall mongodb
$ npm install mongodb@2.2.12
Then, restart the app and it works fine!

Solution B:
Simply, don’t use the ObjectId!! Simple as that!!
Code Refactor:
var docId = id;
Blogs.findOne({‘_id’:docId}).exec()…

Then, restart the app and it works great!

Related article:
Mongoose error: Cast to ObjectId failed for value 583fe2c488cf652d4c6b45d1

Advertisements