Pankaj Barnwal
Pankaj Barnwal

Reputation: 79

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.

Upvotes: 5

Views: 3681

Answers (3)

Gaurav Joshi
Gaurav Joshi

Reputation: 1054

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

Upvotes: 7

Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 12995

If you are using Mongodb driver , you can do like

var ObjectID = require('mongodb').ObjectID
var id = new ObjectID(req.params.id); // Hex 

Mongoose

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");

console.log(id);
console.log(_id);

//4edd40c86762e0fb12000003
//4eb6e7e7e9b7f4194e000001

How to use in findById

Campground.findById(id.toString(), function (err, found) { 
        // Do Whatever you like after getting data
 } );

Upvotes: 1

fawee
fawee

Reputation: 395

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

Upvotes: 1

Related Questions