How to change localhost to MongoDb and Heroku host - mongodb

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

Related

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

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.

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

Unable to connect to mLab database from self-hosted Parse

TL;DR: I can get my parse dashboard talking to my locally-hosted Parse server and mongo db instance but cannot get the parse server to talk to the mLab-hosted database.
I am going through the Parse migration guide and have got mongo DB, parse-server-example and parse-dashboard running locally. When I use the following details in the parse index.js file I can successfully connect the dashboard and see the test items in the database:
databaseURI: 'mongodb://localhost:27017/dev',
cloud: __dirname + '/cloud/main.js',
appId: '1',
masterKey: '1',
serverURL: 'http://localhost:1337/parse'
I have installed mongo db locally and when connecting to my mLab instance with the shell I can see the database content. When I use that same mLab connection string in the databaseURI parameter within index.js the dashboard can no longer see the database content and the /test page on the locally-hosted parse server.
The Parse Migration Guide states...
Go to the Security & Keys section of App Settings in your Dashboard
and take note of the File Key and Master Key values. Pass that into
the ParseServer constructor in index.js. You no longer need to use a
client key with Parse Server.
I can find those keys but I cannot see where to put the File Key into the index.js.
I also do not understand why those keys are required if the locally-hosted Parse server and mLab database know nothing about them.
steps :
create your user/pwd in the mLab/mongo instance
get the db URL from mLab dashboard
connect using a command lib client to verify what parse-server will
use. this verifies the user/pwd you will use below...
go back to 'parse-server.js' to config it for mongo/remote
var databaseUri = $what-was-on-cli-client-above
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://<db.....
....

setting up graphQL on OpenShift

I'm learning how to set up a server on OpenShift that uses node, express, GraphQL and Postgres and I need some help.
When trying to set up the GraphQL Server I've been following this and it works on my local machine:
import Express from 'express';
import GraphQL from 'express-graphql';
import Schema from './db/GQLschema';
const app = Express();
app.use('/graphql', GraphQL({
schema: Schema,
pretty: true,
graphiql: true
}));
...
I'm using the server.js template provided by OpenShift so the above changes to:
...
self.app = express();
self.app.configure(function() {
self.app.use('/public', express.static(__dirname+'/public'));
self.app.use('/graphql', GraphQL({
schema: Schema,
pretty: true,
graphiql: true
}));
});
...
But this doesn't work when pushed up to OpenShift. I get 'Internal Server Error' instead of the graphiql interface.
I'm new to this, but here are some guesses as to what it might have to do with:
Connecting to database
Missing dependencies
Connecting to database: I have 2 json config files. One for my local machine which is connected using a port-forward SSH tunnel to OpenShift. That works fine. The other is one for production. In it I have all the strings for the database name, user, port, host, and password, that OpenShift provided me. I'm using the config library which looks at NODE_ENV to decide which config json file to use. I set the NODE_ENV variable on OpenShift to production. When I query it, it shows all the correct strings. Is there something else I need to set?
Missing dependencies: To keep it neat, I am keeping my back-end code separate from my front-end code. So the back-end code has only the express, graphql, sequelize, config, and pg stuff installed. Do I need something else to make the graphiql page work? Also, I put all the /node_modules/ in the .gitignore file -- I assumed that OpenShift installs them post push. Was that the right thing to do?
Would appreciate any help!
OK - I solved it by doing the following:
in the openshift cli tools turn on error logs
rhc tail -a <yourappname>
This will give you some clues. In my case it was a message from express-graphql "unresolved promise". After researching I found that if you install and save es-promise and add this line to the top of the server.js file:
require ('es6-promise').polyfill();
Hope that helps someone else!

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();