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.
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
Remove var ObjectId = mongoose.Types.ObjectId(id);
and it should work
...And pass the id instead of the ObjectId in the findById function :)
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