MongoDB查询User模型报Cast to ObjectId failed错误如何解决
错误产生原因
- Mongoose的
findById方法仅接收字符串形式的_id值、ObjectId类型值作为入参,你在调用时传入了{userId:req.params.userId}这个对象,方法会尝试将整个对象转为ObjectId类型匹配_id字段,类型不匹配直接抛出CastError。 - 你输出的friends数组中存在undefined值,是因为当前查询到的用户following数组里包含空字符串
'',使用无效的空字符串调用findById无法匹配到任何用户,就会返回undefined。
修复方案
- 修改用户查询逻辑:如果是按_id字段匹配用户,直接将
req.params.userId传给findById即可,不要包裹对象;如果你的业务里userId是单独的自定义字段,改用findOne方法传入查询条件对象。 - 遍历following数组前先过滤无效的id值,避免查询无结果返回undefined。
- 组装返回数据时过滤掉无效的查询结果,避免解构undefined时报错。
修复后的完整代码如下:
const mongoose = require('mongoose') // 确保已引入mongoose router.get("/friends/:userId", async (req, res) => { try { // 修复点1:按_id查询直接传值,不要包裹对象 const user = await User.findById(req.params.userId); // 如果你是按自定义userId字段查询,改用下面这行 // const user = await User.findOne({userId: req.params.userId}); // 修复点2:先过滤无效id再查询 const validFriendIds = user.following.filter(friendId => { return friendId && mongoose.isValidObjectId(friendId) }) const friends = await Promise.all( validFriendIds.map((friendId) => { return User.findById(friendId); }) ); let friendList = []; // 修复点3:过滤掉查询返回的空值再处理 friends.filter(Boolean).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) } });
内容的提问来源于stack exchange,提问作者Hemmyhtec Creatives
相关产品推荐
相关产品推荐

