Url shortner microservice variable undefined

its not working I cant get the value of inc to be what I want it to be. this has something to do with async? I think becuase its value is being set after Im sending the response too soon or something like that? please give me a hint how to fix this.

app.post("/api/shorturl/new", function (req, res) {
  url = req.body.url;
  var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
  if(!valid) return res.json({error:'Invalid URL'})
  let inc;
  ShortenedUrl.find({}, function (err, foundItems) {
    if (foundItems.length === 0) {
      inc=0;
      console.log("founditems is zero");
      const dbUrl = new ShortenedUrl({
        name: url,
        code: inc,
      });
      dbUrl.save(function (err) {
        if (err) return console.log(err, "there was an error saving it");
        console.log("saved successfully first one code zero");
      });
    } else {
      console.log("there is already items in collection");
      ShortenedUrl.findOne({})
        .sort({ code: "desc" })
        .exec((error, res) => {
          if (!err) {
            inc = res.code + 1;
            console.log("adding new item with code =", inc);
            const dbUrl = new ShortenedUrl({
              name: url,
              code: inc,
            });
            dbUrl.save(function (err, res) {
              if (err) return console.log(err, "there was an error ln 53");
              // saved!
              console.log(`${res} saved success w code `);
            });
          } else {
            console.log(err, "the err");
          }
        })
    }
  })
  res.json({ original_url:url, short_url:inc });
});

You have to move res.json inside relevant callbacks.

Before I made this post I tried to do this, I thought it would work:

      ShortenedUrl.findOne({})
        .sort({ code: "desc" })
        .exec((error, res) => {
          if (!err) {
            inc = res.code + 1;
            console.log("adding new item with code =", inc);
            const dbUrl = new ShortenedUrl({
              name: url,
              code: inc,
            });
            dbUrl.save(function (err, res) {
              if (err) return console.log(err, "there was an error ln 53");
              // saved!
              // console.log(`${res} saved success w code `);
              res.json({ original_url:url, short_url:inc });
            });

and I get

TypeError: res.json is not a function

I found this post

the top answer said the issue is overwriting the response so I changed the name of response variable from res to response but it still doesn’t work:

      ShortenedUrl.findOne({})
        .sort({ code: "desc" })
        .exec((error, res) => {
          if (!err) {
            inc = res.code + 1;
            const dbUrl = new ShortenedUrl({
              name: url,
              code: inc,
            });
            dbUrl.save(function (err, response) {
              response.json({ original_url:url, short_url:inc });
            });

For anyone who might happen to come across the same problem, that stack overflow post I referenced was correct, I was indeed overwriting the response object. The error I was recieving was correctly noted in the console typeError res.json is not a function, as what I was returning from that save method did not have a json method. I mistakenly thought It was the res, but in reality, it was just the object that was being saved to the db returned from the save method … ive updated the code as follows and now its working properly:

app.post("/api/shorturl/new", function (req, res) {
  url = req.body.url;
  var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
  if(!valid) return res.json({error:'Invalid URL'})
  let inc;
  ShortenedUrl.find({}, function (err, foundItems) {
    if (foundItems.length === 0) {
      inc=0;
      console.log("founditems is zero");
      const dbUrl = new ShortenedUrl({
        name: url,
        code: inc,
      });
      dbUrl.save(function (err) {
        if (err) return console.log(err, "there was an error saving it");
        console.log("first one code zero saved");
        res.send({ original_url:url, short_url:inc });
      });
    } else {
      console.log("there is already items in collection");
      ShortenedUrl.findOne({})
        .sort({ code: "desc" })
        .exec((error, response) => {
          if (!error) {
            inc = response.code + 1;
            console.log("adding new item with code =", inc);
            const dbUrl = new ShortenedUrl({
              name: url,
              code: inc,
            });
            dbUrl.save(function (err, savedObj) {
              if (err) return console.log(err, "there was an error ln 53");
              // saved!
              console.log(`${savedObj} saved obj `);
              res.send({ original_url:url, short_url:inc });
            });
          } else {
            console.log(err, "the err");
          }
        })
    }
  })
  // res.json({ original_url:url, short_url:inc });
});

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