fave77 / pbchess

An open-sourced free online chess platform
https://develop.pbchess.ml
GNU General Public License v3.0
43 stars 58 forks source link

working with mongoose means working with promises #76

Closed abhay27chauhan closed 3 years ago

abhay27chauhan commented 3 years ago

Is your feature request related to a problem? Please describe. :bulb: if you are working with mongoose, means you are working with promises. So, you need to handle promise. This is an easy fix but good for long term.

Describe the solution you'd like :sparkles: I suggest instead of this:

connect(mongoURI, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true, });

You should do this:

    mongoose
      .connect(mongoURI, {
        useNewUrlParser: true,
        useUnifiedTopology: true, 
        useCreateIndex: true,
        useFindAndModify: false,
      })
      .then(() => {
        console.log('Connected to mongo db');
      })
      .catch((err) => {
        console.log("Couldn't connect to mongo db, err: ", err);
      });
abhay27chauhan commented 3 years ago

I am a participant of GSSOC21, so please let me know if this is a valid proposal

adi-g15 commented 3 years ago
    mongoose
      .connect(mongoURI, {
        useNewUrlParser: true,
        useUnifiedTopology: true, 
        useCreateIndex: true,
        useFindAndModify: false,
      })
      .then(() => {
        console.log('Connected to mongo db');
      })
      .catch((err) => {
        console.log("Couldn't connect to mongo db, err: ", err);
      });

We may not need the .then, as we have the once handler for 'open' event, so when connected AND open for requests it will console.log Though, yes the catch handler can help.

Also, the title of issue doesn't give anything much about the issue you are pointing, it could have been more to the point, for eg. Handle/Correct/Fix Unhandled Promise Rejection (or Failing to connect to mongodb, or the error name as seen in the case you tag) etc., it will help you in your future issues you create, the current issue is more like telling that it IS the correct way 😅

@abhay27chauhan Or do you also mean changes at any other code too using mongoose ?

abhay27chauhan commented 3 years ago

read this pls, the error handling part - https://mongoosejs.com/docs/connections.html#:~:text=If%20initial%20connection%20fails%2C%20Mongoose,after%20initial%20connection%20was%20established.

you have handle two errors -

  1. if promise is rejected -> using the above code i have proposed
  2. error after initial connection is made -> using the event handlers
fave77 commented 3 years ago

@abhay27chauhan you can use try/catch along with async/await for handling the initial connection error. Also, please mention your discord username.

abhay27chauhan commented 3 years ago

discord username - abhay(P)#3950