How to put an application with MongoDb Atlas on a git? - mongodb

I want to put an application on the MERN stack on the github for my portfolio. My database is on MongoDB Atlas.
To connect to it, I use mongoose.connect ('mongodb + srv: // USERNAME: PASSWORD#cluster0.vtexx.mongodb.net/blog? RetryWrites = true & w = majority', {useNewUrlParser: true, useUnifiedTopology: true});
What should I do with this line so that the person who cloned my repository can evaluate my application, but without knowing my username and password for MongoDB Atlas?

You should have a .env file that contains environment variables like the Mongo username and password. That file should be added to your .gitignore file so that it is not checked into source control.
From this example: https://alligator.io/react/mern-stack-intro/
Your .env file should contain your environment variables:
PORT=3000
DEBUG=true
API_URL=http://localhost:3000
CORS_ORIGINS=http://localhost:8080
APP_SECRET='something secret'
MONGODB_URI=mongodb://localhost/mern-starter
You'd reference these variables in your JS code like so:
const PORT = process.env.PORT || 3000;
You can then check in a file called .env.example that contains the base variable names and some sample values. Users that clone your repo can copy/rename the file to .env and enter their own credentials to run it themselves.

Related

How to connect to Postgres with Kotlin/Ktor with plugin start

I have decided to start learning Kotlin/Ktor. I have created a project in Intellij and selected the Postgres plugin. I'm reading the instructions of how to set it up from the file it created:
/**
* Makes a connection to a Postgres database.
*
* In order to connect to your running Postgres process,
* please specify the following parameters in your configuration file:
* postgres.url -- Url of your running database process.
* postgres.user -- Username for database connection
* postgres.password -- Password for database connection
**/
But I cant figure out where to set the username or password (or url). It refers to a configuration file but I have no idea where that is.
Here are all my file structure if it helps.
All files part 1
All files part 2
All files part 3
I have tried the Navigate - > Search everywhere" option for keywords such as password and postgres but found nothing that looks like where I can configure the password or username.
Any help appreciated.
There is supposed to be an application.conf file in your resources folder, if it is not there, that means you chose your configurations to be in code when you created the project the first time.
Look at the following image: Ktor Project creation, in the bottom it asks where to set up your configurations, choose HOCON file instead of Code. By this way, you will have application.conf file in your resources folder.
In that file, add the following code snippet to configure Postgres:
postgres {
url = "Your URL"
user = "Your USERNAME"
password = "Your PASSWORD"
}
However, for security purposes, you should not write your database credentials as plaintext in your configuration file. For your production, consider using environment variables and configure Postgres like this:
postgres {
url = ${pg_url}
user = ${pg_username}
password = ${pg_password}
}
where pg_url, pg_username, and pg_password are the defined environment variables in your system.
Finally, to access the url, user, and password in your code, Do it like this:
val url = environment.config.property("postgres.url").getString()
val user = environment.config.property("postgres.user").getString()
val password = environment.config.property("postgres.password").getString()
For more info about configuring your project in the file, refer to the documentation. Hope my answer helps.

How to change localhost to MongoDb and Heroku host

so i finish to build my app with mongodb express react native with expo ,
and im trying to change the local host server with port 3000, to real host server with horuko and mongodb.
i was build and connected the mongoDb to heroku like the docs, i go to settings in heroku and paste the momngodb_uri , something like :
mongodb+srv://admin:admin#lior.rva16.mongodb.net/<dbname>?retryWrites=true&w=majority
in my Index server.js i change from local to :
const port = process.env.PORT;// here i dont really have port (i dont know what to put inside)
mongoose
.connect(process.env.MONGO_URI, {///this line is -
>mongodb+srv://admin:admin#lior.rva16.mongodb.net/<dbname>?retryWrites=true&w=majority
useNewUrlParser: true,
useUnifiedTopology: true,
})
this is my env file:
MONGO_URI=mongodb+srv://admin:admin#lior.rva16.mongodb.net/<dbname>?retryWrites=true&w=majority
JWT_SECRET=LKDSLCX9IOZiJS9IAJ768
in my client side all the request url is like:
await indexApi.post("/signout");
and until now i used with NGROK to connect and check my db so the base url until now is been:
export default axios.create({
baseURL: "http://cca1237fb2de.ngrok.io", //ngrok http 3000
});
the problem:
i get errors that all of the is show that is cant connect to the url, he dont find the server url.
(note that with the localhost everything worked correctly)
the question:
how can i connect my app to heroku server
what is my new BaseUrl ? (im tried to do {process.env.MongoDB_Uri} but is also crash...)
the big question is "how can i replace the server from local to real server in heroku with mongo"
lin https://github.com/roeigr7/LIOR
The best way to do this is to have an environment variable that stores your production/staging MONGO_URL. On your local machine you can use dotenv package to pull values from .env files and the environment variables you set on your heroku app deployment.
Local .env
MONGO_URL=mymongourl
You can set environment variables in your heroku app by going to Settings > Config Vars. There should be a button named Reveal Config Vars. Click on that and it will give you an interface to add more environment variables.
Code
const dotenv = require('dotenv')
dotenv.config()
...other code
const mongoURL = process.env.MONGO_URL

How do I store a SQL connection password in Airflow cfg?

In the .cfg file, I connected sql alchemy to Postgres with user: airflow_admin and password: pass:
sql_alchemy_conn = postgresql+psycopg2://airflow_admin:pass#localhost:5432/airflow_backend
How do I anonymize this so that the password doesn't show? Do I create a .env file and store the password as a variable and then reference that variable in .cfg conn string?
I read the following but an example would be helpful: https://airflow.readthedocs.io/en/stable/howto/set-config.html
There are several way to do it:
1. change the configuration file permision to read only by airflow account
2. used airflow by docker mode, and encrpyt the configurationfile by docker secret create and map it.
THe mode 1 is easy and convinent. The mode 2 is flexible and can be used in production environment.
Good luck.
If you think the answer is good, pls up vote

Connecting MongoDB to MERN app

I am in the process of trying to connect my MongoDB to my MERN web application and was wondering the best resource for information on this type of thing. Basically, I have a MERN web app, electron desktop app, and react native mobile app that I am trying to all connect to one MongoDB, but I can't find any information on this that directly answers how it should be wired. I can provide more details if needed.
Make sure you are using the database username and password not the account username and password from Mlab.
In MLab, formerly MongoLab, do the following:
Navigate to Users
Add Database User
Choose your username and password
Now you can test this on the shell with mongo ds061374.mlab.com:61374/yourdb -u <dbuser> -p <dbpassword>.
I hope you have already signed up to mongodb and created a project there.
Below is the integration process to get your MERN application connected to MongoDB online cluster.
Make sure you have the following libraries installed dotenv, mongoose.
Create a folder in your project root directory that will hold your configuration file, Eg config_folder
Create a .js file, Eg dbConnnect.js
Create a create a dotenv file to hold the key for your MongoDB cluster by just creating a fine file on your project root folder and name it .env. NOTE no prefix required while naming this file.
login to your MongoDB and navigate to Projects, select your project then navigate to Databases -> Clusters -> connect -> connect your application -> copy the connection string.
Navigate back to your .env file and create a variable and paste the connection string as shown below.
MONGODB_URI = 'your_connection_string_from_mongoDB'
Inside dbConnect.js add the following code.
const mongoose = require('mongoose')
const dbConnect = async() => {
try {
const connected = await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log(`Connected ${connected.host}`)
} catch (error) {
console.log(`error : ${error.message}`)
}
}
module.exports = {
dbConnect
}
Now you need to call the above block in your server file using the code below.
const { dbConnect } = require('./config/dbConnect')
const dotenv = require('dotenv')
dotenv.config()
dbConnect();
That's the end of the integration process. It worked for me and I hope it'll help.
If you want to connect your MongoDB with the MERN app you can use the mongoose package for that, let me tell you the steps.
Packages you will need : mongoose,nodemon,express
Note*:- Make sure you know how to use Mongo Atlas.
1- Step 1- create db.js file in your main directory.
//import mongoose
const mongoose = require("mongoose")
//make connection variable
const connection = mongoose.connect("mongodb+srv://<username>:<password>#cluster0.en0mzco.mongodb.net/?retryWrites=true&w=majority")
//the username and password will be the same as your cluster username and password.
//export the connection variable
module.exports={
connection
}
2- Step 2- Create index.js file for the server
//import express
const express = require("express")
//import connection from db.js
const {connection} = require("./db.js")
//define post
const port = 4000
const app = express()
//Start server code
app.listen(port,async()=>{
try{
//mongo db all operations are done in an async manner so make sure you use async/await
await connection
//on the successful connection this msg will show in your terminal
console.log("Connected to db")
}catch(err){
console.log(err)
}
console.log("Server is runnig on port number",port)
})
3- Step 3- Make sure you add this line to your package.json inside scripts
"server":"nodemon index.js"
//Now run the server by running this command in your terminal
npm run server
Also, I am putting my youtube video for full stack web development, where you will get all the processes of how to do all the setup.
Youtube Link: Fullstack web development in 1hour

Deploying app with private info on Heroku

I have a Node project on Github which I deploy on Heroku and use MongoDB for database needs.
I have a URL from Mongo, which I connect to using the username and password. It all works perfectly when I run it on my local system, 'cause I can hardcode my username and password (or even use process.env.USER_NAME).
My question is, how do I pass in these values on Heroku. It is synced with my github and I don't want to make my user name and password public.
You want to use environment variables.
This can be done from within each Heroku app
1: Go to your app's settings: https://dashboard.heroku.com/apps/:yourApp/settings
2: Click Reveal Config Variables and you will see an area to add or edit your environment variables
3: Within your app you will have access to these variables by accessing your processs.
var dbURL = process.env.databaseUrl,
dbUsername = process.env.dbUsername,
dbPassword = process.env.dbPassword;
4: For development purposes you will still need to keep those variables in an env variable. Install the dotenv npm module.
npm install dotenv
// appRoot/.env
dbURL=localhost:27017
dbUsername=tacoman
dbPassword=ILoveTacos
// approot/server.js
require('dotenv').load();