我有一个具有以下路由的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;
}
})
})
当我使用邮递员测试路线时,我总是会收到此错误:
{ [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命令正在请求猫鼬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);
您必须在参数字符串中直接传递该ID,例如id="5e441654a8b2e25bfa3d4507"
。尝试传递不带引号的id=5e441654a8b2e25bfa3d4507
。
请尝试以下操作:
var mongoose = require('mongoose');
...
var myId = new mongoose.Types.ObjectId(req.params.id)
Book.findById(myId).then(function(book) {
...
它应该起作用。