【问题标题】:Cast to ObjectId failed for value "6283201d60c794631cd1ba33\n" (type string) at path "_id" for model "Post"对于模型 \"Post\" 的路径 \"_id\" 中的值 \"6283201d60c794631cd1ba33\\n\"(类型字符串),转换为 ObjectId 失败
【发布时间】:2022-10-05 02:28:48
【问题描述】:

我正在做一个社交媒体项目,并在我发送喜欢/不喜欢的帖子请求时得到这个

CastError:模型“Post”的路径“_id”处的值“6283\n”(类型字符串)转换为 ObjectId 失败 在 model.Query.exec (E:\social-media-app-mern\node_modules\mongoose\lib\query.js:4639:21) 在 model.Query.Query.then (E:\social-media-app-mern\node_modules\mongoose\lib\query.js:4738:15) 在 processTicksAndRejections (node:internal/process/task_queues:96:5) { 消息格式:未定义, stringValue: '"6283\n"', 种类:'ObjectId', 值:'6283\n', 路径:'_id', 原因:BSONTypeError:传入的参数必须是12字节的字符串或 24 个十六进制字符或整数 在新的 BSONTypeError (E:\social-media-app-mern\node_modules\bson\lib\error.js:41:28) 在新的 ObjectId (E:\social-media-app-mern\node_modules\bson\lib\objectid.js:66:23) 在 castObjectId (E:\social-media-app-mern\node_modules\mongoose\lib\cast \objectid.js:25:12) 在 ObjectId.cast (E:\social-media-app-mern\node_modules\mongoose\lib\schema\objectid.js:247:12) 在 ObjectId.SchemaType.applySetters (E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1135:12) 在 ObjectId.SchemaType._castForQuery (E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1567:15) 在 ObjectId.SchemaType.castForQuery (E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1557:15) 在 ObjectId.SchemaType.castForQueryWrapper (E:\social-media-app-mern\node_modules\mongoose\lib\schematype.js:1534:20) 演员表 (E:\social-media-app-mern\node_modules\mongoose\lib\cast.js:336:32)
在 model.Query.Query.cast (E:\social-media-app-mern\node_modules\mongoose\lib\query.js:5062:12), 值类型:'字符串' }

路线:

const express = require("express");
const { createPost, likeAndUnlikePost } = require("../controllers/post");
const { isAuthenticated } = require("../middlewares/auth");

const router = express.Router();

router.route("/post/:id").get(isAuthenticated, likeAndUnlikePost);

module.exports = router;

楷模:

const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
  caption: String,
  image: {
    public_id: String,
    url: String,
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  likes: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
  ],
  comments: [
    {
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
      comment:{
        type: String,
        required: true,
      }
    },
  ],
});
module.exports = mongoose.model("Post", postSchema);

likeAndUnlikePost:

  try {
    const post = await Post.findById(req.params.id);

    if (!post) {
      return res.status(404).json({
        success: false,
        message: "Post not found",
      });
    }

    if (post.likes.includes(req.user._id)) {
      const index = post.likes.indexOf(req.user._id);

      post.likes.splice(index, 1);

      await post.save();

      return res.status(200).json({
        success: true,
        message: "Post Unliked",
      });
    } else {
      post.likes.push(req.user._id);

      await post.save();

      return res.status(200).json({
        success: true,
        message: "Post Liked",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
    console.error(error)  }
};

【问题讨论】:

  • 6283201d60c794631cd1ba33\n,这里的 \n 是不必要的,请检查你从哪里得到这个。此错误通常发生在 MongoDB 期望某种类型的数据但获取其他类型时,这里 MongoDB 期望 ObjectId 但获取字符串。
  • @AnveegSinha 如何将字符串转换为 ObjectId?
  • mongoose.Types.ObjectId('YOURSTRINGVARIABLE');
  • 我仍然认为您的问题是因为 id 末尾的额外 \n ,您能否在这个问题中添加代码的前端部分?

标签: node.js mongodb mongoose get httprequest


【解决方案1】:

首先验证_id是否存在。然后尝试将字符串 _id 转换为 ObjectId

mongoose.Types.ObjectId(req.params.id);

【讨论】:

    【解决方案2】:

    好吧,我的朋友,我看到了问题!

    与其他答案不同,我实际上运行了您的代码。
    似乎它工作得很好。 您无需更改其中的任何内容!!!
    不过有一个问题,
    看看你得到的错误:

    Cast to ObjectId failed for value "6283 "

    这个“6283”的值是多少 “?那就是问题所在!
    好像您有一个 id 为“6283”的用户 ”。
    这意味着,它包含数字和一个空白,所以空格使它成为字符串。
    所以,虽然我说你的代码没有问题,但你的代码可能有问题用户模型,你没有在这个线程中向我们展示过。

    答案 - 如何解决它

    因为我还没有看到你的用户模型,所以我会做出 2 个猜测:

    1. 您希望/希望您的 User _id 字段为 ObjectId 类型。如果是这样,找出为什么你有一个奇怪的 _id 值为“6283”的用户 ",基本上是两个错误:A)你的 _id 是由数字组成的,即数字类型,而想要 ObjectId 类型。B)你有一个100% 意外空间溜进去了。了解它是如何到达那里的。
    2. 您希望/打算将 User _id 字段设为 Number 类型。如果是这样,那么这又分为两个问题:A)您的用户 _id 仍然包含一个空格,这是我假设的100% 意外.找出它的来源。 B)您的用户 _id 由数字组成,这是您想要的,但请查看 Post 模型中的数组字段,其中包含对您的用户的引用。您在那里声明用户的 _id 字段的类型对象标识,而不是数字,因此不匹配。

    【讨论】:

      【解决方案3】:

      在代码中的某处,您已将字符串值分配给 _id(类型为 ObjectId

      【讨论】:

        猜你喜欢
        • 2019-10-10
        • 2021-09-06
        • 1970-01-01
        • 2023-02-16
        • 2022-09-29
        • 1970-01-01
        • 2021-05-12
        • 2019-06-26
        • 1970-01-01
        相关资源
        最近更新 更多