Undefined when doing find() in URL Shortener

My Schema looks like this:

const urlShortSchema = new mongoose.Schema({
  URL: { type: String, required: true },
  Short: Number
});

and the model is:

let urlShort = mongoose.model("urlShort", urlShortSchema);

I want to write a function that will return either (the maximum Short + 1) or 1 if no rows yet in database.

Here is my attempt:

As you can see in the console I am getting undefined and I cannot work out why - I have tried all sorts of things but am getting nowhere.

My full code link is https://replit.com/@AlanBra/boilerplate-project-urlshortener#index.js

Thank you for replying.

I added a row for testing:

const newUrl = new urlShort({URL: 'abc', Short:7});
newUrl.save(function(err, data) {
    if (err) return console.error(err);
console.log(`Saved:${data}:`);
});

I tweaked the function like this:

but as you can see I’m getting undefined.

I tried changing the post line to be:

app.post('/api/shorturl', async function(req, res, next) {

and put await into these lines like this:

  if (await isValidUrl(passedUrl)) {
    console.log("VALID");
    const newShort = await getMaxShort();
    console.log(`newShort:${newShort}:`);
  }

but got the same results.

I’m sure it’s something simple but I just can’t see it

I managed to resolve the issue! :slightly_smiling_face:

  1. I made the route call asynchronous:
app.post('/api/shorturl', async function(req, res) {
  1. I changed the function:
  async function getMaxShort() {
    return await urlShort.find({})
            .sort('-Short')
            .limit(1)
            .then(function(maxShort) {
                    if (maxShort.length === 0) {
                      return 1;
                    }
                    else {
                      return maxShort[0].Short + 1;
                    }
                  }
                 );
  }
  1. I call the function:
const newShort = await getMaxShort();

It now works!