jingteng
jingteng

Reputation: 2611

How to save the return from Mongoose exec function?

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?

Upvotes: 0

Views: 49

Answers (2)

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18919

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;

Upvotes: 1

Sven.hig
Sven.hig

Reputation: 4519

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

Upvotes: 1

Related Questions