I am going with an online course, there's a part where the instructor says he is trying to find/ validate a user using User.findOne
and passes some conditions to find the requested user. To pass the value, he uses object destructuring. Heres the specific code:
const token = req.header("Authorization").replace("Bearer ", "");
const decoded = jwt.verify(token, "secret key here!");
// issue is here, look at the second property of the findOne function's argument.
const user=await User.findOne({_id: decoded._id, 'tokens.token': token})
The instructor is using a string key in 'tokens.token'
. He's saying that, mongodb
will loop over the all the tokens available in specified user
object to check if the given token
matches.
And if you are wondering, here's an example of a single user
which contains auth tokens:
{
"name": "Prottay",
"_id": "5e27f23b6b549b4c28b8ac35",
"password": "$2a$08$gUfMwk6TNWViHihrcxjKg.8EXD04lLkGIWXqzrf8wYokdLQXHxpdy",
"tokens": [
{
"_id": "5e27f23b6b549b4c28b8ac36",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTI3ZjIzYjZiNTQ5YjRjMjhiOGFjMzUiLCJpYXQiOjE1Nzk2NzYyMTl9.-PWXzlEoPlEZn9F_awtzqrXOtByxUCW9RCdchHF1yKE"
},
{
"_id": "5e280429596e742dcc2f9e30",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTI3ZjIzYjZiNTQ5YjRjMjhiOGFjMzUiLCJpYXQiOjE1Nzk2ODA4MDl9.7W-QZ55Cc3NFd_-NPyJ0VW_5F1UVrDWAV4xHX63D6tc"
},
{
"_id": "5e280435596e742dcc2f9e31",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTI3ZjIzYjZiNTQ5YjRjMjhiOGFjMzUiLCJpYXQiOjE1Nzk2ODA4MjF9.vppisFiNNC_DYHtGK0IURzEOCCC5zcWl1v9yD6l1D4I"
}
],
"__v": 3
},
To me it looks like by using 'tokens.token': token
instructor is trying to loop over on the user's tokens array to match the correct token.
Am I right? If I am how can he be using loop in object destructuring?