0

I have checked all these things :-

  • Ip whitelist
  • Async funtion try catch
  • Account password
  • Nodejs version

Now still I am getting the error

Mongo connection code

  const connectDB = async() =>{
    await mongoose.createConnection(URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,   })   
 .then(() => console.log("Database connected!"))
 .catch(err => console.log(err));
    }

Post request

connectDB();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(cor());
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('/', indexRouter);
// app.use('/users', usersRouter);

app.post('/shorturl',async (req,res)=>{
  let shortUrl = new shorturl({full:req.body.fullurl})
  console.log("Saving!!")
   await shortUrl.save()
    
   .then(()=>{ console.log("Inserted!!"); res.send(shortUrl.short)}).catch(error => console.log("ERROR"));
  //await shorturl.create({full:req.body.fullurl}) 
  //  if(shortUrl == null )return res.sendStatus(404);
    
})

GET

Its making a get req but not returning any thing.Not even any error its just making get req again and again.

app.get('/:shortUrl',async (req,res)=>{
   try{ 
    const shortUrl = await shorturl.findOne({ short: req.params.shortUrl })
   .then(()=>{
      if(shortUrl == null) return res.sendStatus(404);
      res.redirect(shortUrl.full);
   })
  }
  catch{(error)=> console.log(error)};
})
Hrithik Jaiswal
  • 74
  • 1
  • 2
  • 9
  • Does this answer your question? [MongooseError: Operation \`shorturls.insertOne()\` buffering timed out after 10000ms?](https://stackoverflow.com/questions/68594647/mongooseerror-operation-shorturls-insertone-buffering-timed-out-after-10000) – Vega Nov 03 '21 at 03:07

1 Answers1

1

Generally when there is only one connection mongoose.connect() is used, whereas if there is multiple instance of connection mongoose.createConnection() is used.

In your case, I see you have used createConnection(). So, you can not directly access your models through mongoose.model, as they were defined "in" different connections.

If you want to proceed with createConnection(), refer to this answer.

Else, you can simply use mongoose.connect()

Ex:

const mongoose = require("mongoose");

//do not use .then() with async/await. use a try/catch block to catch errors
const connectDB = async() =>{
      try {
        const conn = await mongoose.connect(URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,   });
        console.log("Database connected!"));
        return conn;  
      } catch (error) {
          //handle error
          console.error(error);
          return error;
      }
   }

// ideally you should only start the server if the the database connection was successfully established
connectDB().then(() => {
      app.listen(process.env.PORT, () =>
      console.log(`Example app listening on port ${process.env.PORT}!`),
    );
});

PS: In most simple projects, you needn't worry about specifying different read or write settings, pool sizes, separate connections to different replica servers etc., that's why .connect exists.

However, if you have more demanding requirements (e.g. for legal or performance reasons), you will probably have to use .createConnection.

Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26