【问题标题】:CastError: Cast to ObjectId failed for value "id goes here" at path "_id" for model "Article"CastError:模型“Article”的路径“_id”处值“id 转到此处”的值“id 转到 ObjectId”失败
【发布时间】:2017-05-25 12:44:48
【问题描述】:

我遇到了一些奇怪的事情,想知道是否有人可以帮助我。我有一个 MEAN 应用程序,它能够完美地从 MongoDB 中检索所有记录,但是当我尝试通过 id 仅检索 1 条记录时,我得到了 CastError。我什至尝试降级我的 Mongo 版本,但问题仍然存在。任何帮助都会很棒。谢谢

var express = require('express');
var router = express.Router();

var Article = require('../models/article');


/* GET users listing. */
router.get('/', function(req, res, next) {
  Article.getArticles(function (err, articles) {
      if (err) {
          console.log(err);
      } else {
          res.json(articles);

      }
  });
});

router.get('/:id', function(req, res, next) {
  Article.getArticleById(req.params.id, function (err, article) {
      if (err) {
          console.log(err);
      } else {
          res.json(article);
      }
  });
});

module.exports = router;

var mongoose = require('mongoose').set('debug', true);

var articleSchema =  mongoose.Schema({

    title: {
        type: String,
        index: true,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    category: {
        type: String,
        index: true,
        required: true
    }
});

var Article = module.exports = mongoose.model('Article', articleSchema);

// Get all articles
module.exports.getArticles = function (callback) {
    Article.find(callback);
};

// Get article by ID
module.exports.getArticleById = function (id, callback) {
     Article.findById(id, callback);

};

[CastError: Cast to ObjectId failed for value "58753da5d192f1aa25ebdd00" at path "_id" for model "Article"]
  message: 'Cast to ObjectId failed for value "58753da5d192f1aa25ebdd00" at path "_id" for model "Article"',
  name: 'CastError',
  stringValue: '"58753da5d192f1aa25ebdd00"',
  kind: 'ObjectId',
  value: '58753da5d192f1aa25ebdd00',
  path: '_id',
  reason: undefined,

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    问题可能出在您的视图模板引擎上。确保正确定义到特定 id 的路由。

    【讨论】:

    【解决方案2】:

    这似乎是最新版本的 Mongoose 中的一个已知错误。我建议降级到 4.7.2:

    https://github.com/Automattic/mongoose/issues/4867

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 2015-07-16
      • 2014-06-20
      • 2020-11-19
      • 2017-08-18
      • 2016-11-11
      • 2017-03-26
      • 2017-05-26
      • 2020-05-20
      相关资源
      最近更新 更多