skip to Main Content

I am trying to loop though all users data in my mongo database and check and see if an email is in the database. The loop currently works and correctly identifies if an email is in a database but the problem is once I verify the email exist I get the id of the same object and use findById() to find the specific object the email was found in then update it. Once I find the object when I try and print the result I got from the first find() it logs undefined but when I log it before the findById() method it logs the result without no problem. Why is this happening and how can I log the previous result after invoking findById(). Take a look at the comments on my code to understand the question better. Thanks in advance.

const Users = require('pathToSchema')

const email = '[email protected]'

Users.find()
  .then(async(result) => {
    for (var i = 0; i < result.length; i++) {
      if (result[i].email == email) {
        //this prints result successfully
        console.log(result[i])
        Users.findById(result[i].id)
          .then((result2) => {
            //this prints undefiend
            console.log(result[i])
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        if (i === result.length - 1) {
          console.log('email not found')
        }
      }
    }
  })
  .catch((err) => {
    console.log(err)
  })

2

Answers


  1. From the code snippet it looks like you are trying to print a value from result and not result2. result is not available inside the findById() method callback handler.

    Login or Signup to reply.
  2. Continuing the discussion from the comments, you can use the findOneAndUpdate method in mongodb to find a user with a given email and update. With this, you will not have to find the user before you update. You can do that in a single DB command.

    Users.findOneAndUpdate({email: '[email protected]'},{updates},{options});
    

    This will return the original document before update. If you need the updated document in the response, pass returnNewDocument: true in the options.

    Link to the documentation for this function
    https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search