Mongoose: TypeError: hex is not a function

I am developing an application to easily save data using mongoose after you get stuck in this error

CastError: Cast to ObjectId could not set the value "{_id: 'id'}" along the path "_id" for the model 'foo'

I tried to use mongoose.Types.ObjectId , as suggested by various threads, one partcular: https://stackoverflow.com/a/212220/2/2 , but now I get a new error:

TypeError: hex is not a function.

Here is the important 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"); }); 

As a newbie, I can make a simple mistake here, any help would be appreciated.

+6
source share
3 answers

Over the past 2 days, I am also getting the same issue, and this is due to a version issue

I used this version of "mongodb": "^ 2.2.19",

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

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

and it starts to work, so I think they removed the hex function and others, so after installing this version in your .json package, try not to use ^ before the version name just add "mongodb": "2.1.7", "mongoose": "4.4.8" and set

+6
source

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

+1
source

If you are using the Mongodb driver, you can do it 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 } ); 
+1
source

Source: https://habr.com/ru/post/1013880/


All Articles