我希望返回结果为true,但是javascript表示其为false。有人可以解释一下为什么吗?
这是console.log的日志
5a8f1df35f65a820f4dc56ed 5a8db5d449c0572dbc60548c
假
5a91e3de5b8d6d18580c9aff 5a8db5d449c0572dbc60548c
假
5a91e3f45b8d6d18580c9b00 5a8db5d449c0572dbc60548c
假
5a8db5d449c0572dbc60548c 5a8db5d449c0572dbc60548c
.get('/selected/board', function (req, res) {
var isExist = false;
Board.findById({ _id: req.query._id })
.then((board) => {
board.users.forEach(element => {
console.log(element == req.user._id)
console.log(element, req.user._id)
});
// res.json(board);
})
.catch((err) => {
res.status(404).json('Cant download.')
})
})
编辑
元素:“ 5a8f1df35f65a820f4dc56ed” req.user._id:“ 5a8db5d449c0572dbc60548c”
假
元素:“ 5a91e3de5b8d6d18580c9aff” req.user._id:“ 5a8db5d449c0572dbc60548c”
假
元素:“ 5a91e3f45b8d6d18580c9b00” req.user._id:“ 5a8db5d449c0572dbc60548c”
假
元素:“ 5a8db5d449c0572dbc60548c” req.user._id:“ 5a8db5d449c0572dbc60548c”
真正
元素:“ 5a8f1df35f65a820f4dc56ed” req.user._id:“ 5a8db5d449c0572dbc60548c”
假
元素:“ 5a91e3de5b8d6d18580c9aff” req.user._id:“ 5a8db5d449c0572dbc60548c”
假
元素:“ 5a91e3f45b8d6d18580c9b00” req.user._id:“ 5a8db5d449c0572dbc60548c”
假
元素:“ 5a8db5d449c0572dbc60548c” req.user._id:“ 5a8db5d449c0572dbc60548c”
真正
最佳答案
board.users
中的元素具有属性id
,其类型为ObjectId("45465456464")
,因此您要执行的比较遵循以下规则:
+--- Operand ObjectId(...)
|
v
ToPrimitive(element) == B <---- String from the request.
因此,此条件始终为
false
element == req.user._id
看看这个文档
Loose equality using ==
另一种方法是转换为
String
element.toString() == req.user._id