【问题标题】:500 error: Cast to ObjectId failed for value500 错误:转换为 ObjectId 的值失败
【发布时间】:2017-11-13 01:22:03
【问题描述】:

我从服务器收到错误。

"{"message":{"message":"模型 \"Comment\"","name":"CastError" 的路径 \"_id\" 中的值 \"authors\" 转换为 ObjectId 失败, "stringValue":"\"authors\"","kind":"ObjectId","value":"authors","path":"_id"}}"

我有模型:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var commentSchema = new Schema({
  author: String,
  title: String,
  text: String,
  favorite: Number
});

var Comment = mongoose.model("Comment", commentSchema);

module.exports = Comment;  

从 Angular 2 编写的客户端,我使用以下方法发送请求:

getAuthors() {
         return this.http.get(this.appConfig.urlServer + "/comment/authors")
             .map((response: Response) => response.json());
}  

我有下一条路线:

var express = require("express");
var mongoose = require("mongoose");
var Comment = require("../models/comment");
var router = express.Router();

router.get("/comment/authors", getAuthorsOfComments);

module.exports = router;

function getAuthorsOfComments(req, res) {
    Comment.find({}, 'author', function(err, authors) {
    if (err) {
      res.status(500).json({
        message: err
      })
    }

    if (authors) {
      res.status(200).json({
        authors: authors
      })
    }
  })
}

请帮帮我。我不知道为什么我会出错。

更新 1。

评论集合中的条目。 第一条:

{
    "_id" : ObjectId("59269000483977cefe7961e0"),
    "author" : "test",
    "title" : "title of text",
    "text" : "Big text",
    "favorite" : 1
}

第二个条目:

{
    "_id" : ObjectId("5926901b483977cefe7961f2"),
    "author" : "test2",
    "title" : "title of text",
    "text" : "Big text",
    "favorite" : 5
}

【问题讨论】:

  • 你能从评论集合中发布一些条目吗?
  • 是的,我可以。我更新了我的帖子。
  • 您确定,您使用的是您发布的确切代码吗?您的代码看起来很好,应该可以正常工作。

标签: node.js mongoose


【解决方案1】:

实际问题在于您的查询方法,您没有正确查询数据库并且没有正确调用回调函数。我会重写你的查询代码。

function getAuthorsOfComments(req, res) {
    Comment.find({}, {author: 1}).then( function(err, authors) {
    if (err) {
      res.status(500).json({
        message: err
      })
    }

    if (authors) {
      res.status(200).json({
        authors: authors
      })
    }
  })
}

{author: 1} 告诉 mongoDB 只返回作者。如果您输入 0 而不是 1,mongoDB 将返回所有字段,但不返回作者。

【讨论】:

  • 我没有看到 OP 的查询有任何问题。他的查询很好。
  • 我找到了错误的原因。我在路由的其他方法中写了不正确的url,所以我没有执行对数据库的查询。
猜你喜欢
  • 2020-12-16
  • 2022-08-15
  • 2019-06-11
  • 2022-01-23
  • 2020-10-13
  • 2020-08-25
  • 2013-03-24
  • 2018-03-04
  • 2021-06-27
相关资源
最近更新 更多