问题描述
我遇到一些奇怪的事情,想知道是否有人可以帮助我.我有一个MEAN应用程序,能够完美地从MongoDB检索所有记录,但是当我尝试通过ID检索仅1条记录时,我得到了CastError.我什至试图降级我的Mongo版本,但问题仍然存在.任何帮助将是巨大的.谢谢
I'm experiencing something a little strange and was wondering if someone can help me out. I have a MEAN application that is able to retrieve ALL records from MongoDB perfectly but when I try to retrieve just 1 record by id, I'm getting a CastError. I even tried to downgrade my version of Mongo but the problem still persist. Any help would be great. Thanks
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,
推荐答案
这似乎是最新版本的Mongoose中的一个已知错误.我建议降级到4.7.2:
this seems to be a known bug in the latest version of Mongoose. I'd recommend downgrading to 4.7.2:
https://github.com/Automattic/mongoose/issues/4867
这篇关于CastError:转换为ObjectId失败,原因是值"id go here"在路径"_id"处对于模型"Article",的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!