Mongoose Extract Found Records

Mongoose Extract Found Records
0

#1

Hi,

I am working with Mongoose, and I run the following query after posting a verify token and email. The idea is that the user will use a secretToken emailed to them, alongside their email, to turn their account active. However, I am having trouble finding the Mongoose record based on the findOne function:

router.post("/verify", function(req, res, next){
    const { secretToken } = req.body;
    const { email } = req.body;

    //find account that matches the secret token
    const user = User.findOne({ "email": email, "secretToken" : secretToken });

    // this does not seem to get the right records!
    console.log(user);

    //If we fail to match token and email, i.e. user is NULL
    if(!user) {
        req.flash("error", "Verification has failed, please try again");
        res.redirect("verify");
    }

});

Any guidance is much appreciated!


#2

If I’m not mistaken the findOne method is asynchronous (please double check the documentation), so user is always undefined when you console.log it because that line always executes before findOne returns.

You can use the error-first callback pattern with findOne to get user:

User.findOne({ ...options }, (user) => {
  // Do things with user
});

Or, if memory serves well, findOne returns a thennable Promise object:

User.findOne({ ...options})
  .then((user) => {
    // Do things with user
  });

Or if you are more comfortable with the async-await pattern:

(async function() {
  let user = await User.findOne({ ...options});

  // Do things with user
})()

I hope that helps!


#3

Thank you! This makes a lot of sense - I was having trouble trying to store the returned record in the variable “user”.

I guess I can just use the call back to directly do things with the user variable.

Thanks again!