Problem with passing one test in a project URL Shortener Microservice

Hello! I can’t figure out why my " When you visit /api/shorturl/<short_url> , you will be redirected to the original URL." test fails, it seems to work just fine when i’m trying to do everything manually, could somebody help me pls? Code below

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

// Basic Configuration
const port = process.env.PORT || 3000;


app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: "false" }));
app.use(bodyParser.json());


const mongoose = require('mongoose');

mongoose.set('strictQuery', true);

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

var urlencodedParser = bodyParser.urlencoded({ extended: false })


const urlSchema = new mongoose.Schema({
  originalUrl: {
    type: String,
    required: true,
  },
  short: {
    type: Number,
    //unique: true,
    
  }
})

let urlModel = mongoose.model("urlModel", urlSchema);

app.post('/api/shorturl', (req, res) => {
  console.log(req.body)
  
  inputUrl = req.body.url;

  let baseshort;


    var urlRegex = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(urlRegex);

if (inputUrl.match(regex)) {
  urlModel.findOne({originalUrl: inputUrl})

        
  
        .exec((error,searchresult) => {
          console.log(searchresult)
          
          if(!error && searchresult != undefined){
            res.json({ original_url : inputUrl, short_url : searchresult.short});
          }
          if(searchresult == undefined){
            urlModel.countDocuments({short: 1},function(err, count){
              
              if(count === 0)
                baseshort = 1;             
              else
                baseshort = count+1;
              
              if(!err && count !=undefined){
                
                urlModel.findOneAndUpdate(
                  { originalUrl: inputUrl },
                  { originalUrl: inputUrl, short: baseshort},
                  { new: true, upsert: true },
                  (error, savedUrl) => {
                    if (!error) {
                    res.json({ original_url : inputUrl, short: baseshort});
                    }
                  }
                )
                
              }
            })
          }
          
        })
} else {
  res.json({ error: 'invalid url' })
}




  

})


app.get('/api/shorturl/:input', (request, response) => {
  let input = request.params.input

  
  urlModel.findOne({short: input}, (error, result) => {
    console.log(result)
    if(!error && result != undefined){
      response.redirect(result.originalUrl)
    }else{
      response.json('URL not Found')
    }
  })
})

app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});



The error is on this line of your code. countDocuments here counts number of documents that matched the query ‘{short: 1}’, this counts only documents with short value of 1.


You should instead use an empty document ’ {}’ as query parameter if your want to count total documents, which is the correct method to get unique short urls according to your method.

urlModel.countDocuments({},function(err, count){

source

1 Like

:sweat_smile: I only tested it after that, the test still fails even after fixing the previous error.

There is another error

in the above code, res.json key ‘short’ is wrong

res.json({ original_url : inputUrl, short: baseshort});

it should be ‘short_url’.

res.json({ original_url : inputUrl, short_url: baseshort});

1 Like

I’ve fixed the errors you’ve mentioned, but i can’t pass the test anyway, what it could be?

can you send me the link for your replit project?

ln81: res.json({ original_url : inputUrl, short: baseshort});

you forgot to correct the json statement, you are still using ‘short’, use ‘short_url’

Sorry m8, my bad probably, i’ve checked again and replit didn’t save it, i’m 100% sure i’ve changed it how you said, btw, i reloaded the page, fixed the key and tests are passing now, huge huge thanks to you, wish you all the best!