Thursday, November 14, 2019

node.js - why does Javascript comparison not work with objects?





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.


Answer



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()) {
...
}

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...