简体   繁体   中英

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.

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 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
 } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM