Why Isn't my MongoDB saving entries?

I am doing the URL shortener exercise, and it’s going okay. I’m having a bit of trouble with saving entries to MongoDB, however. Here’s my (relevant) code.

//Initializing the urlSchema for use later

const schema = mongoose.Schema;

const urlSchema = new schema({
  original_url: {type: String, required: true},
  short_url: {type: Number, required: true}
})

//sending Post data to the server, and saving to MongoDb

app.post("/api/shorturl/new", function(req, res) {
  var newEntry = new URL({
    original_url: req.body.url,
    short_url: Math.floor(Math.random() * 1000) + 1
  });
  newEntry.save(function(err, doc){
        if(err) res.json(err);
        else    res.send('Successfully inserted!');
      });
res.send(req.body.url)
});

Couple things to note. Yes, I know that it’s not returning a JSON object with the new URL and the original url. I can do that, but I’d rather pull them from MongoDB.

I am 99% sure I’m connected properly, my connection link is saved in the env file, and I am using mongoose.connect(process.env.MONGO_URI)

Any ideas why this isn’t working?

Can you link to the full project code? Then we can test things out.

1 Like

sure, no problem. Here is the link to the code, without access to the env files. I trust you, of course, but since this is a public forum, perhaps including the env file would be counterproductive.

No worries. I have my own mongoose db with my own credentials I can use to test your code.

1 Like

@FCCStudent I first recommend upgrading your packages to the following:

		"mongodb": "^3.2.6",
		"mongoose": "^5.6.4",

and then connect to mongoose with:

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

Once you make those changes, you will need to move:

res.send(req.body.url)

to be in the else condition code block instead of res.send('Successfully inserted!') or you will not see the url as a reponse on the page.

You’re awesome, Randall, this fix worked perfectly. Thanks so much for figuring that out! On to the challenge for me! :slight_smile: