Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: TypeError: hex is not a function

I am developing a simple data persistence app using mongoose, After getting stuck on this error

CastError: Cast to ObjectId failed for value "{ _id: 'id' }" at path "_id" for model 'foo'

i tried to use mongoose.Types.ObjectId as suggested by various threads, one partcular : https://stackoverflow.com/a/17223701/4206519, but now I am getting a new error:

TypeError: hex is not a function.

Here is a relevant part of the code:

app.get('/campgrounds/:id', function(req, res){
    var id = req.params.id;
    var ObjectId = mongoose.Types.ObjectId(id);
    Campground.findById(ObjectId, function(err, found){
        if (err) {
            console.log(err);
        } else {
            //render show template with that campground
            res.render('show.ejs', {campground: found});
        } 
    });
});

app.listen(3000, function(){
    console.log("server has started");
});

Being a newbie, i may be making a simple mistake here, any help will be appreciated.

like image 916
Pankaj Barnwal Avatar asked Jan 08 '17 14:01

Pankaj Barnwal


2 Answers

From last 2 days i am also getting the same problem and it's due to the version issue

i was using these version "mongodb": "^2.2.19",

"mongoose": "^4.7.6", and getting the error that Hex is not a function

then i change the version to "mongodb": "2.1.7", "mongoose": "4.4.8"

and it start working so i think they have removed the hex function and other so try after installing this version in your package.json dont use ^before version name just add "mongodb": "2.1.7", "mongoose": "4.4.8" and install

like image 177
Gaurav Joshi Avatar answered Sep 19 '22 22:09

Gaurav Joshi


Remove var ObjectId = mongoose.Types.ObjectId(id); and it should work ...And pass the id instead of the ObjectId in the findById function :)

like image 24
fawee Avatar answered Sep 20 '22 22:09

fawee