我有一个nodejs express路由器,路由如下:
router.get("/book/:id", function(req, res){
Book.findById(req.params.id).then(function(book){
if (book) {
res.json(book);
} else {
res.send("Book Not found");
}
}).catch(function(err){
if (err) {
console.log(err);
res.send(err);
throw err;
}
})
})
当我使用postman测试路由时,我总是得到这样的错误:
{ [CastError: Cast to ObjectId failed for value "5e441654a8b2e25bfa3d4507" at path "_id" for model "Book"]
stringValue: '"5e441654a8b2e25bfa3d4507"',
kind: 'ObjectId',
value: '5e441654a8b2e25bfa3d4507',
path: '_id',
reason: [TypeError: hex is not a function],
message: 'Cast to ObjectId failed for value "5e441654a8b2e25bfa3d4507" at path "_id" for model "Book"',
name: 'CastError',
model: Model { Book } }
看起来findById命令请求的是mongoose objectId类型,而不是字符串,我尝试了在线解决方案(从堆栈和其他社区),我找到了类似于:
ObjectId = mongoose.Types.ObjectId
ObjectId = mongoose.Schema.ObjectId
ObjectId = mongoose.mongo.ObjectId
然后,解决方案建议这样做:
id = new ObjectId(req.params.id)
Book.findById(id)
仍然不能处理hex is not a function
错误
有没有人遇到这个错误并设法修复它?注意,我使用的是:
mongodb cloud hosting, version 4
mongoose 5.8.11
nodejs 4.2.6
这是我的书模型,如果它有帮助的话:
const schema = new mongoose.Schema({
title: {
type: String,
require: true
},
author: {
type: String,
require: true
},
numberPages: {
type: Number,
require: false
},
publisher: {
type: String,
require: false
}
});
module.exports = mongoose.model('Book', schema);
发布于 2020-02-13 14:43:11
似乎是节点驱动导致了这个问题(发现我使用的是4.6的旧节点版本),我升级了我的nodejs版本,现在它可以工作了,谢谢大家。
发布于 2020-02-12 15:32:48
请尝试执行以下操作:
var mongoose = require('mongoose');
...
var myId = new mongoose.Types.ObjectId(req.params.id)
Book.findById(myId).then(function(book) {
...
应该能行得通。
发布于 2020-02-12 15:36:31
您必须在参数字符串中直接传递该id,就像下面的id="5e441654a8b2e25bfa3d4507"
。尝试传递不带引号的id=5e441654a8b2e25bfa3d4507
。
https://stackoverflow.com/questions/60191669
复制相似问题