猫鼬的findById命令的问题

时间:2020-02-12 15:25:22

标签: node.js mongoose

我有一个具有以下路由的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);

3 个答案:

答案 0 :(得分:0)

请尝试以下操作:

var mongoose = require('mongoose');
...
var myId = new mongoose.Types.ObjectId(req.params.id)
Book.findById(myId).then(function(book) {
...

应该可以。

答案 1 :(得分:0)

您必须直接在参数字符串中传递该ID,例如id="5e441654a8b2e25bfa3d4507"。尝试传递不带引号的id=5e441654a8b2e25bfa3d4507

答案 2 :(得分:0)

似乎是节点驱动程序引起了这个问题(发现我使用的是旧版本的4.6),我升级了我的nodejs版本,现在可以正常工作了,谢谢大家。