【问题标题】:Implement follow/unfollow in Node.js在 Node.js 中实现关注/取消关注
【发布时间】:2022-02-11 16:47:35
【问题描述】:

我是初学者,我想在我的应用中创建关注/取消关注功能。

router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(otherUser.followers.includes(req.userInfo._id)){
       
        return res.json({message: "Already following user"});
    }
    req.userInfo.updateOne({$push: {followings: req.params.id}});
    otherUser.updateOne({ $push: {followers: req.userInfo._id}});
    res.json({message: "following user"});
    console.log(otherUser.followers);

})
.catch((e)=>{
    res.json(e);
})})

运行代码时,它会收到“关注用户”的消息,但不会添加到数据库,即 Mongodb(我正在使用 MERN 堆栈)

这段代码似乎没有执行。

req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});

我在这里做错了什么?

【问题讨论】:

    标签: javascript node.js express mongoose mern


    【解决方案1】:

    我认为这是因为 req.userInfo 和 otherUser 是一个不可变的 mongo 对象。试试这个(假设“用户”是你的模型对象):

    user.updateOne(
       { _id:  req.userInfo._id},
       {$push: {followings: req.params.id}
    )
    
      user.updateOne(
           { _id:  otherUser._id},
           { $push: {followers: req.userInfo._id}}
        )
    

    注意:在比较 _id 时,请检查您是存储为 objectId 还是 string。

    供您参考:Comparing mongoose _id and strings

    【讨论】:

    • 它似乎只有在它后面跟着 .then() 方法时才有效。或者它跳到res.json({message: "following user"});
    【解决方案2】:

    嗯,这似乎有效

    router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{
    
    user.findById(req.params.id)
    .then((otherUser)=>{
        if(!otherUser.followers.includes(req.userInfo._id)){
            Promise.all([
                user.updateOne({_id:req.userInfo._id}, {$push: {followings: req.params.id}}),
                user.updateOne({_id: otherUser._id},{$push: {followers: req.userInfo._id}})
            ]).then(()=>{
                res.json({message: "following user"});
            })
            .catch((e)=>{
                res.json(e);
            }); 
        }else{
            return res.json({message: "Already following user"});
        }
    })
    });
    

    但如果有人解释之前出了什么问题会更好,因为我说我是初学者,希望得到反馈。

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多