我正在使用 mongoose 开发一个简单的数据持久化应用程序,在遇到此错误之后
CastError: Cast to ObjectId failed for value "{ _id: 'id' }" at path "_id" for model 'foo'
我尝试按照各种线程的建议使用 mongoose.Types.ObjectId
,其中一个是:https://stackoverflow.com/a/17223701/4206519 ,但现在我收到一个新错误:
TypeError: hex is not a function.
这是代码的相关部分:
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");
});
作为一个新手,我可能在这里犯了一个简单的错误,任何帮助将不胜感激。
最佳答案
从前两天我也遇到了同样的问题,这是由于版本问题
我正在使用这些版本 "mongodb": "^2.2.19",
" Mongoose ": "^4.7.6", 并得到 Hex 不是函数的错误
然后我将版本更改为 “mongodb”:“2.1.7”, “ Mongoose ”:“4.4.8”
它开始工作,所以我认为他们已经删除了十六进制函数和其他,所以在安装这个版本后尝试 在您的 package.json 中不要使用 ^before 版本名称只需添加 “mongodb”:“2.1.7”, “ Mongoose ”:“4.4.8” 并安装
关于javascript - Mongoose:TypeError:十六进制不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533926/