const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
var app = express();
const bodyParser = require('body-parser');
const shortenerRouter = express.Router();
const Schema = mongoose.Schema;
require('mongoose-currency').loadType(mongoose);
const shortUrlSchema = new Schema({
longUrl: String,
shortUrl: {type: String}
})
var ShortUrls = mongoose.model('ShortUrls', shortUrlSchema);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', shortenerRouter);
shortenerRouter.route('/')
.get(function(req, res, next) {
res.json({user: "moi"})
})
app.post('/api/postlongurl', function (req, res, next) {
const url = 'mongodb://localhost:27017/UrlShortener';
mongoose.connect(url, {useNewUrlParser: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log("Connected correctly to server");
var recordUrl = new ShortUrls({longUrl: req.body.longUrl, shortUrl: "test1"})
recordUrl.save((err, data) => {
if (err) res.send(err)
else {
res.json({ original_url: req.body.longUrl, short_url: data._id.toString() });
}
});
});
})
const PORT = 8080;
app.listen(PORT)
.on('listening', () => {
console.clear();
console.log('server listening on port:', PORT);
})
.on('error', (err) => {
console.error('### error opening port:', PORT);
console.error(err);
});
When I try the code above I get:
{
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"shortUrl": 1
},
"keyValue": {
"shortUrl": "test1"
}
}
When I change the commands starting in ‘var recordUrl = new shortUrls(…)’ and ‘recordUrl.save(…)’ with:
EDIT: see post below for full code.
ShortUrls.create({longUrl: req.body.longUrl, shortUrl: "test1"}, (err, shortUrl) => {
if (err) return err;
I get: Could not get response
Error: socket hang up
What am I doing wrong?