Help with a constructor in mongodb

I have been working on making a urlshortener for a project and when I try to post to the endpoint I created called: /api/shorturl/new. When I try it says that urlScema isn’t a constructor. I keep looking at it and it looks right to me, here’s a link.
the code I have that is pertenent is this:
```
var mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true });
const Schema = mongoose.Schema;
const urlSchema = new Schema ({
id: Number,
url: String
}, {timestamps: true});

const urlModel = mongoose.model(‘url’, urlSchema);

I'll post the rest of my server code below if that helps.

‘use strict’;

var express = require(‘express’);
var mongo = require(‘mongodb’);
var mongoose = require(‘mongoose’);
var cors = require(‘cors’);
var app = express();
var port = process.env.PORT || 3000;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true });
app.use(cors());
var bodyParser = require(‘body-parser’);
app.use(bodyParser());
app.use(’/public’, express.static(process.cwd() + ‘/public’));

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

// create the database entry
const Schema = mongoose.Schema;
var urlSchema = new Schema ({
id: Number,
url: String
}, {timestamps: true});

const urlModel = mongoose.model(‘url’, urlSchema);
// your first API endpoint…
app.get("/api/hello", function (req, res) {
res.json({greeting: ‘hello API’});
});

app.post(’/api/shorturl/new’ ,(req, res)=>{
let shorten = req.body;
console.log(shorten)
let regex = /[-a-zA-Z0-9@:%+.~#?&//=]{2,256}.[a-z]{2,4}\b(/[-a-zA-Z0-9@:%+.~#?&//=]*)?/gi
if (regex.test(shorten.url)===true) {
console.log(“shortening”)
var short = Math.floor(Math.random()*10000).toString();
let data = new urlSchema(
{
originalUrl: shorten,
shorturl: short
}
);

data.save(err=>{
  if (err) {
        return res.send('error saving to database')
      }
})
return res.json({urlSchema});

} else {
return res.json({“failed”: true, message: “failure”});
}
return res.json({shorten})
})

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

var short = Math.floor(Math.random()*10000).toString();
let data = new urlSchema(
{

This is the problem ^^ Use your model, not your schema, and everything should be ok :smile:

Oh, for the next time, you want to enclose your code between three backticks ( ``` ) to give it a ‘code appearance’, much easier to read ^^

1 Like