Mongoose -- Help to Avoid Nesting

Hello all, I’m working on the URL shortening service and everything seems to be going fine. However, I have found that I have to nest all of these database calls in order to access the data inside each of them. Pretty sure I’m doing something wrong, but I can’t figure out how to read the information otherwise, and the lessons in the actual curriculum have a lot of the actual calls hidden (which I don’t like).

Here’s what I have got. Any help would be greatly appreciated. A clear example of what I mean–I had to nest the actual save() function INSIDE the count() function because otherwise it seemed to trigger too soon (or, if I used async, I still didn’t know how to actually read the returned data).

function shortenURL(url) {
  // check if url is valid
  // check to see if URL is already in database
  Link.findOne({ original_url: url }, (err, existing_link) => {
    if (err) return console.error(err);
    if (existing_link) {
      // If the link was already in the DB, return it.
      console.log(`${url} was already recorded.`);
      return existing_link;
    } else {
      // If the link was not in DB, create it and assign new short_url
      console.log(`${url} not in database yet.`);
      Link.countDocuments({}, (err, count) => {
        if (err) return console.error(err);
        let link = new Link({ 
          original_url: url, 
          short_url: count 
        });, data) => {
          if (err) return console.error(err);
          return data;

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.