User.findOne() in a collection that is not 'Users'

Asked

Viewed 54 times

0

I wrote an app that has an email verification logic and is triggered when the user makes the registration. I am using two models in Mongoose: one for users and one for authentication token. In token model I store userid:

inserir a descrição da imagem aqui

In my Usercontroller, when the app needs to authenticate the token that was sent to the user’s email, it does so by searching the Token collection. After finding the token, it needs to fetch the userid that is in the template, according to the image above. For this I have a function User.findOne().

I would like to capture the _userid:Objectid("numberos-numeros") that is in the record, but I would like to call it within the function, more or less like this:

User.findOne({ _userID: mongoose.Schema.Types.ObjectId._userID, ref: 'Token' })

My question: is there a way to do this, identify the user in the user collection using a key that is in another collection?

Thank you!

1 answer

3

The answer is simpler than I imagined:

async confirmationPost (req, res) {
    const token_ = req.body.token;
    await Token.findOne({ token:token_ }, function (err, tokenData) {
       if (!tokenData) {
          return res.status(),
       }
       else 
       {     
       tokenUser = tokenData._userId
       User.findOne({ _id: tokenUser }, function (err, user) {
       // logic-logic
       }

:-)

I could capture all the content of the token information, so I just set a variable that went on the server response and picked up _userid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.