Backend API projects: mongo.MongoClient.connect()

Backend API projects: mongo.MongoClient.connect()
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.


#6

MongoDB and Mongoose - Install and Set Up Mongoose

My solution is not accepted eve though it seems corect.
I have mongoose and mongodb installed and my app looks like this:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

mongoose.connect(process.env.MONGO_URI);

mongoose.connection.on('connected', function(){
  console.log('FCC Glitch conected to DB');
});

mongoose.connection.on('error', function(err){
  console.log('Error connecting to DB ', err);
});

app.use(express.static('public'));

app.use(function(req, res, next){
  console.log(`${req.method} ${req.path} - ${req.ip}`);
  next();
});

app.use(bodyParser.urlencoded({extended: false}));


app.get('/', function(req,res){
  res.sendFile(__dirname+'/views/index.html');
});

app.get('/json', function(req, res){
  
    res.json({message: process.env.MESSAGE_STYLE === 'uppercase' ? "Hello json".toUpperCase() : "Hello json" });
    
});

app.get('/now', function(req, res, next){
  req.time = new Date().toString();
  next();
}, function(req, res){
  res.json({time: req.time});
});

app.get('/:word/echo', function(req, res){
  res.json({echo: req.params.word});
});

app.get('/name', function(req, res){
  res.json({name: `${req.query.first} ${req.query.last}`});
});

  
app.post('/name', function(req, res){
  res.json({name: `${req.body.first} ${req.body.last}`});
});



// This would be part of the basic setup of an Express app
// but to allow FCC to run tests, the server is already active
/** app.listen(process.env.PORT || 3000 ); */

//---------- DO NOT EDIT BELOW THIS LINE --------------------

 module.exports = app;

Is there something I’m not doing right?


#7

Turns out I was still using the express boilerplate on Glitch for the mongoose and mongodb challenges.

Thanks to @alpox who helped me see that.