Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does Javascript comparison not work with objects? [duplicate]

I have simple code here.

The intention of it is to verify the user with the user who wrote the post and allow the verified user to edit the post.

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

The console says:

557c6922925a81930d2ce 'object'
557c6922925a81930d2ce 'object'

Which means they are equal in value and also equal in types.

I tried with == too, but that also doesn't work.

I am suspecting there needs to be something done to compare objects, but I don't know exactly what I should do.

like image 210
Keon Kim Avatar asked Jul 08 '15 12:07

Keon Kim


2 Answers

Javascript, when asked to compare two object, compare the address of the object, not the object himself. So yes, your objects have the same value, but are not in the same place in memory.

You can try to extract the id in new variable and compare that (or convert them to string and compare the strings).

Examples:

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

Or

if(req.user._id.toString() === post.author.user_id.toString()) {
    ...
}
like image 155
DrakaSAN Avatar answered Oct 06 '22 01:10

DrakaSAN


People have mentioned toString(), but mongo also has it's own methods for ObjectIds. You can use:

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

like image 25
chrisbajorin Avatar answered Oct 06 '22 00:10

chrisbajorin