【问题标题】:Mongoose: CastError on querying incorrect ObjectId for nested objectMongoose:为嵌套对象查询不正确的 ObjectId 时出现 CastError
【发布时间】:2017-01-08 15:22:04
【问题描述】:

我有以下架构

var Topic= new Schema({
  text: String,
  topicId: String,
  comments: [{type: Schema.Types.ObjectId, ref:'Comment'}]
});

var Comment = new Schema({
   text: String
});

我正在编写 RESTFul API,它将根据主题 ID 和评论 ID 为我提供评论详细信息

/topics/{id}/comments/{id}

以下是从Mongo获取数据的函数

getCommentsById: function(req, resp){
    req.db.Topic.findOne({"topicId": req.params.topicId})
      .populate({path:"Comments", match:{"_id": req.params.commentId}})
      .exec(function(err, topic){
        if(err) {
            return resp.status(500).json({
                message: 'Error when getting Topic.',
                error: err
            });
        }
        if (!topic) {
            return resp.status(404).json({
                message: 'No such Topic'
            });
        }
        if (!topic.comments || topic.comments.length==0) {
            return resp.status(404).json({
                message: 'No such Comment'
            });
        }
        resp.json(topic.comments[0]);
    });
}

如果我指定正确的评论 ID,代码可以正常工作,但如果我在 URL 中指定不存在的评论 ID,则会出现以下错误

{
  "message": "Error when getting Topic.",
  "error": {
    "message": "Cast to ObjectId failed for value \"57c738b66d790f0c1bdb179\" at path \"_id\"",
    "name": "CastError",
    "kind": "ObjectId",
    "value": "57c738b66d790f0c1bdb179",
    "path": "_id"
  }
}

这里有什么问题以及如何解决?有没有更好的方法来查询所需的对象?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    问题不在于您指定了一个不存在的评论 ID。这是您指定的字符串无法转换为有效的 ObjectId。您的测试字符串“57c738b66d790f0c1bdb179”是一个 23 个字符的十六进制字符串。长度应为 24。

    如果您想在尝试查询之前进行验证,您可以通过多种不同的方式进行验证。这是一个例子:Can I determine if a string is a MongoDB ObjectID?

    【讨论】:

    • 谢谢。虽然答案已经被接受,你能告诉我上面的代码是否是获取嵌套记录的正确方法吗?
    • 对我来说看起来不错,但我不使用猫鼬,所以我不是最好的人。使用本机 mongodb,我只需使用 $lookup 或使用第二个查询来检索子数据。
    猜你喜欢
    • 2013-06-03
    • 2021-03-14
    • 2023-03-25
    • 2021-09-05
    • 2020-06-18
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    相关资源
    最近更新 更多