0

If I have a structure

{
   "__v": 0,
   "email": "[email protected]",
   "password": "dfsdfsdf",
   "_id": "5864a681c02817571564ddeb",
   "tokens": [
      {
         "access": "auth",
         "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dfsdfsdgsdg3423h4jhj23.7oKGPLMAnSBMYRFTCj-xLwfqIx4q3ZPorM0CNxT3OYA",
         "_id": "5864a681c02817571564ddec"
      }
   ]
}

I want the token inside of tokens(array) how do I do it in JS?

User.find({
        [WHAT GOES HERE?]


    }).then((result) => {return result;}).catch((e) => {return "error"})

User is the mongoose model of the schema I've created.

What goes in the find query part?

2 Answers 2

1

Using the dot(.) notation -

User.find({
    'tokens.token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dfsdfsdgsdg3423h4jhj23.7oKGPLMAnSBMYRFTCj-xLwfqIx4q3ZPorM0CNxT3OYA'
}).then((result) => {return result;}).catch((e) => {return "error"})

And I'm guessing the tokens are unique for a user so you could use findOne() instead of find().

Sign up to request clarification or add additional context in comments.

Comments

0

It's quite easy if you have the userId or if you are querying for a specific data.

The userId here is the userId you are looking for.

User.find({ id : userId}, {tokens : 1}).then((result) {
    console.log(result);             // here result will return you the tokens array.  
    console.log(result[0].token);    // to fetch the token
}).catch((e){return "error"})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.