This question already has answers here:
Object comparison in JavaScript [duplicate]

(10个答案)


5年前关闭。




我这里有简单的代码。

其目的是与撰写帖子的用户一起验证用户,并允许经过验证的用户编辑该帖子。
exports.edit = function(req, res){
    Post.findById(req.params.post_id, function(err, post){
        if(err){
            return res.json({
                type:false,
                message:"error!"
            });
        }else if(!post){
            return res.json({
                type:false,
                message:"no post with the id"
            })
        }else{
            console.log(req.user._id, typeof req.user._id);
            console.log(post.author.user_id, typeof post.author.user_id);
            if(req.user._id === post.author.user_id){ // doesn't work!!
                return res.json({
                    type:false,
                    message:"notAuthorized"
                });
            }else{
                return res.json({
                    type:true,
                    message:"it works",
                    data:post
                });
            }
        }
    });
}

控制台说:
557c6922925a81930d2ce 'object'
557c6922925a81930d2ce 'object'

这意味着它们的值相等,类型也相等。

我也尝试过==,但这也不起作用。

我怀疑需要做一些比较对象的事情,但是我不知道该怎么做。

最佳答案

Javascript,当要求比较两个对象时,比较对象的地址,而不是对象本身。因此,是的,您的对象具有相同的值,但不在内存中的相同位置。

您可以尝试提取新变量中的id并进行比较(或将其转换为字符串并比较字符串)。

例子:

var id_edit = req.user._id,
    id_post = post.author.user_id;
if (id_edit === id_post) {
    //...
}

要么
if(req.user._id.toString() === post.author.user_id.toString()) {
    ...
}

07-24 18:54
查看更多