J Moss
J Moss

Reputation: 205

mongoDB, mongoose, cannot connect to DB

First time using mongoDB. Trying to connect to my cluster that i just created on atlas however i keep getting errors

keys.jss

module.exports = {
    mongoURI: 'mongodb+srv://john:<********>@mern-shopping-i5abd.mongodb.net/testretryWrites=true&w=majority'
};

I might be following an outdated tutorial so certain things might be 'unnecessary'

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

const app = express();

// Bodyparser Middleware
app.use(bodyParser.json());

// DB config
const db = require('./config/keys').mongoURI;

// Connect to Mongo
mongoose
    .connect(db, {useNewUrlParser: true} )
    .then(() => console.log('monogoDB Connected...'))
    .catch(err => console.log(err));

    const port = process.env.PORT || 5000;

    app.listen(port, () => console.log('Server started on port ${port}'));

Rather than displaying port '5000' i would get an error (different each time)

Upvotes: 1

Views: 92

Answers (1)

Evan Bechtol
Evan Bechtol

Reputation: 2865

Here is how it would look with a function as a callback, instead of using promises. Notice that I also moved the app startup inside the callback function. This ensures that the app only starts up when we successfully connect to the DB.

I also moved the DB options (2nd parameter in the connect method), into a variable. This way, it's easy to find and can be modified in one place, if necessary. Ideally, you'd keep all your DB config in a single file, and reference it in other files as needed. Separate concerns :)

const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

// Bodyparser Middleware
app.use(bodyParser.json());

// DB config
const db = require('./config/keys').mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};

// Connect to Mongo
mongoose
  .connect(db, dbOptions, function(error) {
    // we had an error of some kind
    if (error) {
      console.error(error);

      // better yet, we don't want to app to run without our DB!
      throw error;
    }

    // If we made it here, no errors came up
    console.log('monogoDB Connected...');

    // Start up the app!
    const port = process.env.PORT || 5000;
    app.listen(port, () => console.log(`Server started on port ${port}`));
  });

Here is how it would look with the promise structure:

const express = require( "express" );
const mongoose = require( "mongoose" );
const bodyParser = require( "body-parser" );

const app = express();

// Bodyparser Middleware
app.use( bodyParser.json() );

// DB config
const db = require( "./config/keys" ).mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};

// Connect to Mongo
mongoose
  .connect( db, dbOptions )
  .then( () => {
    console.log( "monogoDB Connected..." );

    // Start the application
    const port = process.env.PORT || 5000;
    app.listen( port, () => {
      console.log( `Server started on port ${port}` );
    } );
  } )
  .catch( err => {
    console.log( err );
    throw err;
  } );

Upvotes: 1

Related Questions