How to have connection

my connection is mongoose.connection.readyState = 2


require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const shortid = require('shortid');
const { connect } = require('mongodb');
const app = express();

// Basic Configuration
const port = process.env.PORT || 3000;

app.use(cors());

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 }));
app.use(bodyParser.json());


mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });

const schemaUrls = new mongoose.Schema({
  original_url: { type: String, required: true },
  short_url: { type: String, required: true }
});
const UrlsIds = mongoose.model('UrlsIds', schemaUrls);

console.log(mongoose.connection.readyState);

// Your first API endpoint
app.post('/api/shorturl/new', function(req, res) {
  let id = shortid.generate();
  let clientReq = req.body.url;
  let regex = new RegExp(/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi);

  
  if(!clientReq.match(regex)){
    res.json({ error: "invalid url" });
  } else {
    let urlsIdsNew = new UrlsIds({
      original_url: clientReq,
      short_url: id
    });

    urlsIdsNew.save((err, data) => {
      if(err){
        console.error(err);
      }
    });

    res.json({ original_url: clientReq, short_url: id });
  }

});


app.get('/api/shorturl/:inputShort', (req, res) => {
  let inputShort = req.params.urlForward;

  UrlsIds.findOne({ short_url: inputShort }, (err, result) => {
    if(!err && result != undefined){
      res.redirect(result.original_url);
    } else {
      res.json('invalid url');
    }
  });
});

app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});

how to have mongoose.connection.readyState = 1 ???

Connecting to Mongo is asynchronous, it takes some time. You log the connection status right after attempting to open a connection, so it’s no ready yet. Try putting the log in a setTimeout for example, and wait two seconds before logging:

setTimeout(() => {
  console.log(mongoose.connection.readyState)
}, 2000)

You an also add a connected eventListener to the connection:

mongoose.connection.on('connected', () => {
  console.log('connected');
  console.log(mongoose.connection.readyState); //logs 1
});

does work, thank you

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.