0

I am trying to save the return from the following function:

let maxNum;

const result = Url.find({})
 .sort({short_url: - 1})
 .select('short_url')
 .exec((err, data) => {
 console.log('what is data', data)
   if (err) return console.log(err);
   console.log('what is data here', data[0].short_url)
   maxNum = data[0].short_url;
 });

    console.log("resultsssss", result);
    console.log('give me maxnum', maxNum);

What I am getting back is:

resultsssss undefined
give me maxnum undefined
what is data [ { _id: 5ed434038de5842a1b14c44d, short_url: 2 },
  { _id: 5ed432937439e628e98e43e4, short_url: 1 },
  { _id: 5ed57d1dbd11721236587e2b } ]
what is data here 2

You can see if I log inside the exec then I get the data but I can't get the whole thing outside of that and keeps giving me undefined. How can I get the data so I can save it to a variable outside of this function?

2 Answers 2

1

The exec call is asynchronous so by the time you console.log, the function has not completed running yet.

Simply move your console.log into the callback of the exec call.

let maxNum;

const result = Url.find({})
 .sort({short_url: - 1})
 .select('short_url')
 .exec((err, data) => {
   if (err) return console.log(err);

   console.log('what is data', data)

   console.log('what is data here', data[0].short_url)
   maxNum = data[0].short_url;
   console.log('give me maxnum', maxNum); 
 });

or use await statement:

    const result = await Url.find({})
     .sort({short_url: - 1})
     .select('short_url')
     .exec();

    // access whatever you need
    const maxNum = result[0].short_url;
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah but I need it to be outside as I will need to use the value to do something with it hence why I saved it to result variable
Got it! Thank you. Just deleted err and data as it's not defined.
no prob, please remember to mark the answer as correct if it helped solve your question.
1

your promise doesn't return the result you have to add somthing like .then(if(user){return user})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.