I wrote the below code so far but it seems like “newUrl” is not created or saved in mongoDB.
Could anyone help me on this?
'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.MONGO_URI, { useNewUrlParser: true }, (error, client) => {
console.log("Successfully connected to MongoDB");
})
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'));
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/views/index.html');
});
app.use(bodyParser.urlencoded({ extended: false }))
//crete model
const Schema = mongoose.Schema;
const urlSchema = new Schema({
original_url:{type:String,required:true},
shortid: { type: Number},
});
let Url = mongoose.model('Url', urlSchema);
app.post('/api/shorturl/new', (req, res) => {
let originalUrl = req.body.url;
var number = Math.floor(Math.random()*10000).toString();
let newUrl = new Url({
original_url:originalUrl,
shortid: parseInt(number),
}
);
newUrl.save((err, data) => {
if (err)
throw err
console.log(data)
})
return res.json({"original_url":newUrl.original_url,"short_url":newUrl.shortid});
})
app.listen(port, function () {
console.log('Node.js listening ...');
});