You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js社交项目Unfollow功能遇CastError报错求助

解决Next.js社交媒体项目Unfollow功能的CastError问题

问题场景

在开发Next.js社交媒体项目的取消关注功能时,遇到以下错误:

CastError: Cast to Array failed for value "[]" (type Array) at path "followers" because of "TypeError"

涉及代码

User模型(后端Mongoose)

const mongoose = require("mongoose")

const schema = mongoose.Schema(
    {
     followers : {
            type : [mongoose.Schema.objectId],
            ref : "User",
        }
)
module.exports = mongoose.model("User", schema);

前端取消关注触发函数

const unFollowUser = async (userId)=>{
    const result = await instance.post(`/user/unfollow/${userId}`, { followers : getUser()})
    console.log(result)
}

后端取消关注路由

router.post('/user/unfollow/:id', async(req,res)=>{
    try{
        const user = await User.findOne({ _id : req.params.id })
        const followers = user.followers.filter( item => item != req.body.followers)
        user.followers = followers
        user.save()
        res.status(200).send({message : "Success"})
    }catch(e){
        console.log(e)
    }
})

问题修复步骤

1. 修正模型中的类型定义错误

Mongoose的ObjectId类型是mongoose.Schema.Types.ObjectId,你写错成了mongoose.Schema.objectId,这会导致Mongoose无法正确解析数组类型,引发转换错误。修改后的模型代码:

const mongoose = require("mongoose")

const schema = mongoose.Schema(
    {
     followers : {
            type : [mongoose.Schema.Types.ObjectId],
            ref : "User",
        }
)
module.exports = mongoose.model("User", schema);

2. 优化前端参数传递逻辑

当前前端传递的{ followers : getUser()}是整个用户对象,后端只需要当前用户的ID即可,修改前端调用:

const unFollowUser = async (userId)=>{
    const currentUser = getUser()
    const result = await instance.post(`/user/unfollow/${userId}`, { currentUserId: currentUser._id })
    console.log(result)
}

3. 替换后端低效且易出错的数组过滤逻辑

直接使用Mongoose的$pull操作符来更新数据库,比先查询再修改更高效,还能避免类型不匹配问题:

router.post('/user/unfollow/:id', async(req,res)=>{
    try{
        // 从目标用户的followers数组中移除当前用户ID
        await User.findByIdAndUpdate(
            req.params.id,
            { $pull: { followers: req.body.currentUserId } },
            { new: true, runValidators: true } // 返回更新后的文档,并运行验证器
        )
        res.status(200).send({message : "取消关注成功"})
    }catch(e){
        console.error(e)
        res.status(500).send({error: e.message})
    }
})

4. 完善错误响应

后端路由中添加错误响应返回,避免前端处于无响应等待状态。


内容的提问来源于stack exchange,提问作者Unnikrishnan KJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 16:25:19