【问题标题】:CastError: Cast to ObjectId failed for value "NaN" at path "_id"CastError:路径“_id”处的值“NaN”转换为 ObjectId 失败
【发布时间】:2017-03-26 05:59:24
【问题描述】:

[ 问题现已解决...答案非常简单...

$scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)}) .$promise.then(

应该阅读:

$scope.article = articleFactory.getArticles().get({
        id: $stateParams.id
    })

我确实尝试过,但由于某种原因,Chrome 正在缓存旧代码 - 做了一个清晰的历史记录,一切都很好。

大“Doh”。

]

我在将我的网站从 json-server 移动到 express / mongo / mongoose 时遇到问题。在 json 上一切正常,但是当我将它移到 express / mongo / mongoose 时似乎出现了一个问题,引发了以下错误:

CastError: Cast to ObjectId failed for value "NaN" at path "_id" 

然后服务器崩溃了……

我可以通过修改路线来阻止崩溃。以前是这样的:

articleRouter.route('/:articleId')
.get(function (req, res, next) {
    Articles.findById(req.params.articleId, function (err, article) {
        if (err) throw err;
        res.json(article);
    });

})

但是如果我添加一个 if 语句来过滤掉 NaN,那么服务器就会运行:

articleRouter.route('/:articleId')
.get(function (req, res, next) {

if (id.match(/^[0-9a-fA-F]{24}$/)) {
        Articles.findById(req.params.articleId, function (err, article) {
        if (err) throw err;
        res.json(article);
    });
}
})

但它不提供传递 id 的“详细信息页面”。我非常怀疑这与猫鼬模式中的类型有关,但我对此很陌生,有点迷茫。

架构如下 - 我已经尝试过使用和不使用 id 字段:

var articleSchema = new Schema({
    _id: {
         type: String,
         required: true,
         unique: true,
         index: true
    },
    headline: {
        type: String,
        required: true,
        unique: false
    }
---blah blah etc---
}

我已经在下面包含了可能相关或不相关的代码,但我 95% 认为这是 Mongoose 的事情。有什么想法吗?

提前致谢 史蒂夫

相关标记是: (在“news.html”中)

<div ng-controller="ArticleController">
<div><a ui-sref="app.newsdetail({id: article.id})">See details</a></div>
</div>

标记:(在“newsdetail.html”中)

<div ng-controller="ArticleDetailController">
{{article.headline}}
{{article.text}}
</div>

控制器是:

.controller('ArticleController', ['$scope', '$stateParams', 'articleFactory', function ($scope, $stateParams, articleFactory) {
'use strict';
  articleFactory.getArticles().query(
      function(response) {
          $scope.articles = response;
      },
      function(response) {
          $scope.message = "Error: "+response.status + " " + response.statusText;
      }
  );
}])

.controller('ArticleDetailController', ['$scope', '$stateParams', 'articleFactory', function ($scope, $stateParams, articleFactory) {
    $scope.article = {};

    $scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)})
        .$promise.then(
            function(response){
                $scope.article = response;
                $scope.showArticle = true;
            },
            function(response) {
                $scope.message = "Error: "+response.status + " " + response.statusText;
            }
    );        
}])

服务是:

.service('articleFactory', ['$resource', 'baseURL',      function($resource,baseURL) {
'use strict';
    this.getArticles = function(){ 
        return $resource(baseURL+"articles/:id",null,{'get':{method:'GET' }}); 
    }; 
}]) 

【问题讨论】:

    标签: angularjs mongodb express mongoose json-server


    【解决方案1】:

    在您的架构中,您正在定义 _id 字段,这是一个“保留”字段,它也是您正在定义 String 的 ObjectId 类型。您应该从架构中删除 _id,它会自动添加(并编制索引)。 另见Mongoose schema documentation

    【讨论】:

    • 感谢您确认 - 我不确定。可悲的是,我已经尝试过,无论有没有,同样的错误不断发生。只是对为什么它不断抛出这个错误感到困惑。此外,当我在 json 服务器中执行此操作时 - id 是在 url 中传递的,但不是在 express 中传递的 - 可能是一些简单而愚蠢的事情,但有点难过。
    • @user3607750 您可以仔细检查您的收藏以查看文档中的字段。
    • 是的,看过了...集合样本:[ { "_id": "580b31df24de442f78a5c9c8", "headline": "News item header 0", "teaser_text": "Some teaser text" ,“teaser_image”:“teaser.png”,“文本”:“页面文本”,“image_1”:“sample_1.png”,“image_2”:“sample_2.png”,“image_3”:“sample_3.png” ,“link_1”:“test.com”,“link_2”:“test.com”,“link_3”:“test.com”,“__v”:0,“更新”:“2016-11-11T23:40: 46.854Z" } - 显然还有很多其他记录,但你明白了。
    • 是的,看起来问题是文档中的 _id 是字符串,.findById 使用了 objectid。
    • 好的...但是我该如何纠正...它似乎自动将其转换为字符串..有没有办法将其转换为合适的格式?我的意思是,当我填充它时,_id 会自动添加。
    猜你喜欢
    • 2014-06-20
    • 2016-11-11
    • 2017-05-26
    • 2020-05-20
    • 2019-01-06
    • 2016-05-06
    • 2018-03-17
    • 2015-07-16
    • 2020-11-19
    相关资源
    最近更新 更多