我这里有简单的代码。
它的目的是与撰写帖子的用户核实用户,并允许经过验证的用户编辑帖子。
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'
这意味着它们的价值相等且类型相同。
我也试过==
,但这也行不通。
我怀疑需要做些什么来比较对象,但我不确切知道应该做些什么。
答案 0 :(得分:6)
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()) {
...
}
答案 1 :(得分:4)
人们提到toString()
,但mongo也有自己的ObjectIds方法。您可以使用:
post.author.user_id.equals(req.user._id)
答案 2 :(得分:3)
您必须比较mongodb标识符对象的字符串表示。
试试这个:
<script>
jQuery(document).ready(function($){
// jQuery code is in here
});
</script>
答案 3 :(得分:2)
在objects
上使用toString()
。
if(req.user._id.toString() === post.author.user_id.toString()) {
答案 4 :(得分:2)
以下将适合您:
req.user._id.toString() === post.author.user_id.toString()
答案 5 :(得分:2)
这个问题已经回答here,但为了明确......
如果您使用underscore,则可以执行
_.isEqual(obj1, obj2);
但是,没有一般的方法可以做到这一点。有关详细信息,请阅读有关SO的其他类似问题。
答案 6 :(得分:0)
您可以通过从要比较的对象中生成json对象来仅比较属性:
JSON.stringify(obj1) === JSON.stringify(obj2)
虽然它不会检查属性的方法和类型,但它是最简单的,可能是实现最快的比较