Backend API projects: mongo.MongoClient.connect()

Backend API projects: mongo.MongoClient.connect()
0.0 0

#1

As a general principle. Is it better to:

  1. set mongo.MongoClient.connect() once and have all your app.get() inside of it doing whatever database operations (not sure where to put the db.close() given async nature); or
  2. have individual mongo.MongoClient.connect() within each app.get(). Perform whatever operation with the database and db.close() it each time within the app.get()

Is there a preferred way of doing it?


#2

``3. Use mongoose and let it manage all connections.


#3

not quite the explanation i was hoping for…

mongoose isn’t on the freecodecamp program. I was hoping to understand this from within the curriculum.


#4

As far as I know this is considered best practice when using mongodb (not Mongoose):

// Make db connection
db.connect(process.env.DB_URL, function(err){
  // Log an error if one occurs
  if(err){
    console.log('Unable to connect to MongoDB');
    process.exit(1);
  }
  // Start the app if the db connection was succesfull
  else{
    app.listen(port, function(){
      console.log('App listening on port', port);
    });
  }
});

You don’t have to close the connection.


#5

Mongoose is introduced in BETA. You can go through those challenges.