Got my URL Shortener Microservice maybe about half way there, and I can remote connect from Node to my mongo db in mLab via Mongoose.
But before I start writing code that reads and writes to the mongo db on mLab database, don’t I need to create a data model first in the database in mLab? Right now the db simply exists and there are no collections in it yet.
If so, don’t I need to do that directly in mLab via the mongo shell? Or is there something else I should be doing first?
BTW, here is my code so far:
var express = require('express')
var app = express()
var path = require('path');
var port = process.env.PORT || 8080;
app.get('/', (req, res, next) => res.sendFile(path.join(__dirname, '/index.html')));
app.set('port', (process.env.PORT || 5000));
app.get('/new/*', function(req, res) {
var shortenme = req.params[0];
console.log("you said " +shortenme);
var amItrue = validateURL(shortenme);
if (amItrue){
console.log("Yup, that's a url!"); // NEED TO WRITE "add me to db" function
connectmongoviamongoose(shortenme);
}
else{console.log("Nope!");};
})
app.get('/', function(req, res) {
var kissmeorkillme = req.params[0];
var amIinDB = validateURL(kissmeorkillme); // NEED TO WRITE "Am I in db?" function
if (amIinDB){
console.log("Redirecting!");
}
else{console.log("Whatever that is, it's not in our database!");};
})
function validateURL(textval) {
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
function connectmongoviamongoose(shortenme){
var target = shortenme;
var mongoose = require('mongoose');
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbuser>:<dbuserPword>@ds159988.mlab.com:59988/urlcntrctr';
mongoose.connect(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("I think I am connected. ")
console.log(target);
});
}
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});