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


this question has answer here:

i have simple code here.

the intention of verify user user wrote post , allow verified user edit 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 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 equal in value , equal in types.

i tried == too, doesn't work.

i suspecting there needs done compare objects, don't know should do.

javascript, when asked compare 2 object, compare address of object, not object himself. yes, objects have same value, not in same place in memory.

you can try extract id in new variable , compare (or convert them string , compare 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()) {     ... } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -