代码之家  ›  专栏  ›  技术社区  ›  Unnikrishnan KJ

由于“TypeError”,路径“pathname”处的值“[]”(类型为Array)转换为数组失败

  •  0
  • Unnikrishnan KJ  · 技术社区  · 1 年前

    我正在进行一个社交媒体项目,使用 next.js .我想实施 unfollow 功能。

    我收到这个错误-->

    CastError:由于“TypeError”,路径“followers”处的值“[]”(类型为Array)的强制转换为数组失败

    在后端,为 User 创建为

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

    当用户点击unfollow按钮时,将调用以下函数。

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

    我想取消关注 userId 我会把我的身份证作为 { followers : getUser()}

    下面是我创建的从跟随者数组中移除id的路径。

    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)
        }
    })
    

    我以这样一种方式创建了我的 follow 按钮,用户的id将保存到另一个用户的追随者数组中。

    的类型 followers 设置为objectId,但在代码中 user.followers = followers 我正在尝试为追随者设置数组值。有人能帮忙吗?

    expxted输出是保存已筛选的 _id 到跟随者的数组

    0 回复  |  直到 1 年前
        1
  •  0
  •   ItsKrish01    1 年前

    你的代码中似乎有一个拼写错误的问题导致了这个错误。让我们一步一步地研究这些问题。

    在Mongoose模式定义中,您有一个小的拼写错误。它应该是mongoose.Schema.objectId,而不是mongoose.Schema.objectId,并带有大写的“O”和“I”。

    更改此项:

    type : [mongoose.Schema.objectId],
    

    对此:

    type : [mongoose.Schema.ObjectId],
    

    有了这些更改,您的代码现在应该可以正常工作了。如果没有,请告诉我