How to define a Mongo Atlas connectionString in node server.js?

85 views Asked by At

I'm trying to create a simple web app for my local dog park.

The web app will allow users to input their name, their dog's name, and the time they plan to attend. Submissions will be displayed on a webpage for others to see so that folks can know who is going and better plan to meet up.

I created the HTML/Javascript code for the website. I got a Node.Js server running with Express. I spun up a database with MongoDB Atlas. To connect the front end to the backend, I tried to get a Node app running on AWS Elastic Beanstalk. This was the area where I had problems. My app would launch, but its health would be marked as critical.

I took a look at the logs and it seems like this is my problem: "The error message indicates that the connectionString variable is not defined. You should define the variable in your server.js file and make sure it contains the correct MongoDB connection string."

Logs are here - https://pastebin.com/RpcZdqzv

Server.Js code is below

const express = require('express');
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());

const uri = "mongodb+srv://MYNAME+MYPASSWORD.s25gw.mongodb.net/dog-park-db?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Add the routes from app.js here
// ...

mongoose.connect(connectionString, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => {
  console.log('Connected to MongoDB');
})
.catch((error) => {
  console.error('Error connecting to MongoDB:', error);
});

const testSchema = new mongoose.Schema({
  message: String
});

const Test = mongoose.model('Test', testSchema);

app.get('/', async (req, res) => {
  try {
    const testDoc = new Test({ message: 'Hello, MongoDB Atlas!' });
    const savedDoc = await testDoc.save();
    res.send(savedDoc);
  } catch (error) {
    res.status(500).send({ error: 'Error connecting to MongoDB Atlas' });
  }
});

client.connect().then(() => {
    app.listen(port, () => {
        console.log(`App listening at http://localhost:${port}`);
    });
}).catch(console.error);

To solve this problem, I believe that I want to define the variable in my server.js file and make sure it contains the correct MongoDB connection string. I want to make sure I've included the necessary environment variable in my Elastic Beanstalk environment configuration, then set the environment variable through the AWS Management Console or using the AWS CLI. I'll need to name the variable MONGODB_URI and set its value to my MongoDB connection string. Then, I want to modify my server.js file to use the MONGODB_URI environment variable and replace the line that initializes the connectionString variable.

That's my current plan for a solution, but implementing it is a little beyond my capabilities. Any help would be appreciated.

1

There are 1 answers

2
FurtiveStranger On BEST ANSWER

Documentation for mongodb atlas using node can be found here

here is the correct format for the uri

mongodb://username:password@host1:port1,...,hostN:portN/database?authSource=admin&...

use variables to store your uri as const mongoUri = process.env.MONGODB_URI

or as I prefer it like this:

const dbname = process.env.DBNAME
const mongoUser = process.env.MONGOUSER
const mongoPassword = process.env.MONGOPASSWORD
const uri = `mongodb+srv://${mongoUser}:${mongoPassword}@yourhost/${dbname}?retryWrites=true&w=majority`
const client = new MongoClient(uri....

Then add value to the corresponding variables to your AWS account/cli

During development, you may want to use dotENV to fill in those variables whilst developing.