Backend API projects: mongo.MongoClient.connect()

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


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?


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


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.


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
    console.log('Unable to connect to MongoDB');
  // Start the app if the db connection was succesfull
    app.listen(port, function(){
      console.log('App listening on port', port);

You don’t have to close the connection.


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