Mongoose TypeError: ShortUrl.exists is not a function

I’m building the URL shortener and I’m facing an issue with trying to use mongoose.

I get the following error when I POST to /api/shorturl/new:

TypeError: ShortUrl.exists is not a function
    at app.post (/app/server.js:54:31)
    at process._tickCallback (internal/process/next_tick.js:68:7)

server.js:

'use strict';

const dns = require('dns');
const promisify = require('util').promisify;
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const randomInt = require('random-int');

const ShortUrl = require('./short-url');

const dbUri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_URL}`;

mongoose.connect(dbUri, { useMongoClient: true });

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("Connected to MongoDB database")
});

const app = express();

app.use(cors());

app.use('/public', express.static(process.cwd() + '/public'));

app.get('/', (req, res) => {
    res.sendFile(process.cwd() + '/views/index.html');
});

app.post("/api/shorturl/new", async (req, res) => {
    const url = req.body;
  
    let isValidUrl = true;
  
    try {
        await promisify(dns.lookup)(url);
    } catch (error) {
        console.log(error);
        isValidUrl = false;
    }
    
    if (!isValidUrl) {
        res.json({ error: 'invalid URL'});
        return;
    }
  
    let randomNumber;

    do {
        randomNumber = randomInt(1, 999999);
    } while (!(await ShortUrl.exists({ number: randomNumber })));

    const newShortUrl = new ShortUrl({ number: randomNumber, url });
    await newShortUrl.save();
    
    res.json({ 
        original_url: url,
        short_url: randomNumber
    });
});

app.get('/api/shorturl/:number', async (req, res) => {
    const { number } = req.params;
    const url = await ShortUrl.findOne({ number });
    res.redirect(url);
});

app.listen(process.env.PORT || 3000);

short-url.js:

'use strict';

const mongoose = require('mongoose');

const shortUrlSchema = new mongoose.Schema({
    number: { type: Number, required: true },
    url: { type: String, required: true }
});

module.exports = mongoose.model('ShortUrl', shortUrlSchema, 'short-urls');

https://foamy-hero-1.glitch.me

Hi, I am not completely sure but I think you should define the schema and the model only once the connection has been established, i.e. inside the callback passed to db.once('open').

Thanks, but that didn’t do the trick :frowning: