Keo*_*Kim 5 javascript node.js
我这里有简单的代码.
其目的是用编写帖子的用户验证用户并允许经过验证的用户编辑帖子.
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
});
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
控制台说:
557c6922925a81930d2ce 'object'
557c6922925a81930d2ce 'object'
Run Code Online (Sandbox Code Playgroud)
这意味着它们在价值上是相等的,在类型上也是相同的.
我也尝试==过,但这也行不通.
我怀疑是否需要做一些事情来比较对象,但我不知道我应该做什么.
Javascript,当被要求比较两个对象时,比较对象的地址,而不是对象本身.所以是的,你的对象具有相同的值,但在内存中不在同一个位置.
您可以尝试在新变量中提取id并比较它(或将它们转换为字符串并比较字符串).
例子:
var id_edit = req.user._id,
id_post = post.author.user_id;
if (id_edit === id_post) {
//...
}
Run Code Online (Sandbox Code Playgroud)
要么
if(req.user._id.toString() === post.author.user_id.toString()) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |