【问题标题】:Cast to ObjectId failed for value (type Object) at path "_id" for model "User" in mongoDBmongoDB中模型“User”的路径“_id”的值(类型对象)转换为ObjectId失败
【发布时间】:2021-10-02 18:50:50
【问题描述】:

我正在尝试使用参数中的userId 来获取特定用户的朋友。

    router.get("/friends/:userId", async (req, res) => {
    try {
    const user = await User.findById({userId:req.params.userId});
    const friends = await Promise.all(
      user.following.map((friendId) => {
        return User.findById(friendId);
      })
     );
    let friendList = [];
    friends.map((friend) => {
      const { _id, username, profilePicture } = friend;
      friendList.push({ _id, username, profilePicture });
    });
    res.status(200).json(friendList)
    console.log(friendList)
    } catch (err) {
    res.status(500).json(err);
    console.log(err)
    }
    });

但我得到了这个错误

    CastError: Cast to ObjectId failed for value "{ userId: '61543261597a97bfdf670f0b' }" (type Object) at path "_id" for model "User"

当我注销以查看时,我的好友数据...

    [
    undefined,
    {
    _id: new ObjectId("6154346027ecc696433f5b86"),
    username: 'Hemmyhtec',
    email: 'emmmmaee@gmail.com',
    password: '$2b$10$wVkZGu4PxlmW3geXfeBwHOxGeK6v7wyjyV7xeLzBNWQSeg5LtA.eW',
    profilePicture: 'logo3.jpg',
    coverPicture: '',
    followers: [ '', '61543261597a97bfdf670f0b' ],
    following: [ '' ],
    isAdmin: false,
    createdAt: 2021-09-29T09:39:44.199Z,
    updatedAt: 2021-10-02T20:25:38.569Z,
    __v: 0
   }
   ]

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    替换这个

    user.following.map((friendId) => {
    return User.findById(friendId);
    

    })

    user.following.map((friendId) => {
    if(!friendId) return
    return User.findById(friendId);
    

    })

    【讨论】:

    • 没有工作给出同样的错误。
    • 你使用的是哪个库?
    • Nodejs、MongoDB 和 React
    • 您能否检查来自friendreq.params.userId_id 是否是有效的对象ID?
    • 我记录了两者但没有得到任何结果,它只是运行那个错误......但这就是我在登录用户的数据中所拥有的。关注者:[“6154346027ecc696433f5b86”],关注者:[“”],_id:“61543261597a97bfdf670f0b”
    【解决方案2】:

    当您使用findById() 时,您应该只传递_id 的值,而不是具有该值的对象userId。像这样更改您的代码:

    const user = await User.findById(req.params.userId);
    

    【讨论】:

    • 也试过了,但同样的错误
    猜你喜欢
    • 2020-12-10
    • 2023-03-28
    • 2021-05-12
    • 2019-06-26
    • 2017-05-23
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多