【问题标题】:Post authorization doesn't work发布授权不起作用
【发布时间】:2018-06-15 23:53:54
【问题描述】:

我正在尝试限制一位用户编辑其他人的帖子的能力。 当我点击“编辑帖子”时,它会更改帖子的作者,是因为“保存”方法还是? 这是我的尝试:

router.put('/posts/:id', passport.authenticate('jwt'), (req, res) => {

Post.findOne({_id: req.params.id}, (err, post) => {
    if (err) throw err;
    if (post.author = req.user._id) {
        post.title = req.body.title,
        post.content = req.body.content,
        post.postImageUrl = req.body.postImageUrl

        post.save((err, updatedPost) => {
            if (err) throw err;
            else {
                res.json({message:'You have successfully updated your post', success: true});
            }
        });

    } else {
        res.json({success: false, message: 'You are not allowed to do this.'});
    }
});

});

我检查了 post.author 和 req.user._id,它们匹配。

【问题讨论】:

  • 这个if (post.author = req.user._id) 不应该是if (post.author == req.user._id) 吗?
  • 那是个问题,但现在它返回作者和用户不匹配,虽然他们是..
  • 它们都是字符串吗?你能提供一个值的样本吗?
  • post.author 是一个引用,req.user._id 是一个对象属性..
  • 我强烈怀疑 post.author 和 req.user._id 可能代表不同的事物。您能否通过发布存储在 mongo 中的帖子和用户文档示例来详细说明您的问题。

标签: express mongoose mean-stack


【解决方案1】:

请检查您的条件以检查当前用户是否是帖子的作者。而不是检查是否相等,您正在尝试分配和更改作者值。

if (post.author = req.user._id)

解决方案:

Mongoose 提供了一个 .equals 方法来检查对象 id 是否相等。这里是 Mongoose 使用的 mongodb-native 驱动程序 .equals 方法的 docs 的链接。

if (post.author.equals(req.user._id))

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 2015-08-09
    • 2013-11-01
    • 2017-06-25
    • 2013-12-11
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多