Url Shortener MongoDB Help

Hello All,

I have been trying to save data to MongDB Atlas for a few weeks now with no luck. I am not sure what I am doing wrong. I have a connection to the database to Glitch, but nothing is saving. I have check that the whitelist is set up too. I have read through the docs for Mongoose, Googled, and searched for videos but nothing seems to answer my question. Any help you can provide is much appreciated.

Below is my code.

Thanks,
Travis

'use strict';

var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');

var cors = require('cors');

var app = express();

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

/** this project needs a db !! **/ 
// mongoose.connect(process.env.MONGOLAB_URI);

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

app.use(cors());

/** this project needs to parse POST bodies **/
// you should mount the body-parser here

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

app.use('/public', express.static(process.cwd() + '/public'));

let urlSchema = new mongoose.Schema({
  original_url: String,
  short_url: String
});

let Url = mongoose.model('Url', urlSchema);

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

app.use(bodyParser.urlencoded({ extended: false }))
  
// your first API endpoint... 

let arrayShortener = [];


app.get("/api/hello", function (req, res) {
  res.json({greeting: 'hello API'});
});

app.post('/api/shorturl/new', (req, res) => {
  res.json({original_url: `${req.body.url}`, short_url: `1`});
  
  let shortenUrl = new Url({
  original_url: `${req.body.url}`,
  short_url: `1`
});
  
  shortenUrl.save(function(err, data) {
    if(err) {
      console.log('not saved')
    } else {
      console.log('saved to database')
    }
  })
});

app.listen(port, function () {
  console.log('Node.js listening ...');
});

What error are you getting in your console log? You can hit log button bottom left corner.

Did you make sure you to provide correct credentials in .env file?

1 Like

Yes, I checked the .env file. I even tried putting the connection in directly.

I keep getting this error:

Content Security Policy: The page’s settings blocked the loading of a resource at https://gray-platypus.glitch.me/favicon.ico (“default-src”).

So I can’t view what it gives me back. I only get this with Glitch. I’m using Firefox as my browser.

This is what I have in the .env file for the connection:

MONGO_URI='mongodb+srv://tvirgil:###@cluster0-7lnox.mongodb.net/test?retryWrites=true'

Obviously I have the actual password instead of ###

Hm that error message is not that helpful.

Maybe try using mlab instead of atlas? I know mlab’s replacement is atlas but setting up a mongo db is still easier with mlab.

Did you also create a user for your database as well? Meanwhile here is my setup with server.js, you can try to spot anything obviously different.

'use strict';

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const isValidUrl = require('./validUrl');

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

/** this project needs a db !! **/
mongoose.connect(process.env.MONGOLAB_URI);
const db = require("./db");
const { checkDuplicate, saveUrl } = require("./db");

// ** Middlewares **
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/public', express.static(process.cwd() + '/public'));

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


// ** Handle Post requests ** 
app.post("/api/shorturl/new", async (req, res) => {
  const { url } = req.body;

  // 1. check if url is valid 
  const address = await isValidUrl(url);

  if (!address) {
    res.json({
      error: "invalid URL"
    })
    return;
  }

  // 2. check if db already contains the url
  const duplicateData = await checkDuplicate(url);

  // 3a. Duplicate record, send back the document
  if (duplicateData) {
    const { original_url, short_url } = duplicateData;

    return res.json({
      original_url,
      short_url
    })
  }

  // 3b. didn't find a duplicate, save it, send back the document
  const document = await saveUrl(url);

  // handle error
  if (!document) {
    return res.json({
      error: "error saving the entered url"
    })
  }
  
  const { original_url, short_url } = document;

  res.json({
    original_url,
    short_url
  })

})


// ** Handle Short Urls **
app.get("/api/shorturl/:short_url", async (req, res) => {
  const { short_url } = req.params;
  const duplicateData = await checkDuplicate(short_url, true);

  if (!duplicateData) {
    return res.json({
      "error": "No short url found for given input"
    })
  }
  
  const { original_url } = duplicateData;
  
  res.redirect(original_url);
});




app.listen(port, function () {
  console.log('Node.js listening ...');
});
1 Like

I don’t think mlab is offered anymore. It redirects me to atlas unfortunately. I see if I can figure anything out by comparing the code. Thanks for helping!

Solved it. The problem was in the package.json file. Packages need to be updated after cloning the freeCodeCamp project template.

1 Like