Connecting MongoDB to MERN app - mongodb

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

Related

How can I get data from a Heroku PostgreSQL database from a Google Cloud Function?

Google does not offer a free PostgreSQL instance, but Heroku does. Because of that, I am wanting to use GCP for everything except the database. Is there any way to connect to a Heroku database from a Google Cloud Function?
I am new to Google Cloud and am familiar with creating and hosting Express apps. I know that with Express, packages like Massive can be used to establish connections like this:
const express = require("express");
const massive = require("massive");
const { CONNECTION_STRING } = process.env;
const app = express();
app.use(express.json());
massive({
connectionString: CONNECTION_STRING,
ssl: { rejectUnauthorized: false },
})
.then((databaseInstance) => {
app.set("database", databaseInstance);
console.log(gradientString.pastel("DB Connected"));
})
.catch((error) => {
console.log(error);
});
but because there is no server, I am not sure how I would go about calling a Heroku database from a Cloud Function. Is that possible?
It is not much different in cloud functions. In the package.json file add dependency to massive:
"dependencies": {
"massive": "^6.10.2"
}
Then follow instructions from Heroku to get the connection string of postgres and use that in the code you shared.

Deno not connecting to mongodb

I'm hosting a test database on mongodb atlas, and I'm trying to connect via a simple deno app, but I keep getting the following error:
failed to lookup address information: Temporary failure in name resolution
I have made sure nothing is blocked in my firewall, and flushed my DNS to make sure it wasn't that. My code is below.
const URI = 'mongodb+srv://testUser:*password*#testdb.byjzd.azure.mongodb.net/TestDB?retryWrites=true&w=majority';
const client = new MongoClient();
await client.connect(URI).catch((err: string) => {
console.log(err);
});
Note: connecting a simple NodeJS app works fine.

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

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.....
....

Meteor database connection

I am trying to connect to my Mongo database which is situated on the machine as my Meteor app. Here are two files in my app:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js:
if (Meteor.isClient) {
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
But I keep getting a "Exception in template helper: ReferenceError: Boxes is not defined" error - any ideas?
How can you connect to a MongoDB with Meteor?
Scenario A: Use the built-in DB as default
This is much simpler than what you did. When you run meteor you actually start a DB with the Meteor server, where Meteor listens on port 3000 and the database on port 3001. The Meteor app is already connected to this database at port 3001 and uses a db named meteor. There is no need whatsoever to fall back to MongoInternals.RemoteCollectionDriver. Just remove that code and change things to:
Boxes = new Mongo.Collection("boxes"); // use default MongoDB connection
Scenario B: Use a different DB as default
Using the MONGO_URL environment variable you can set the connection string to a MongoDB when starting the Meteor server. Instead of the local port 3001 database or an unauthenticated connection you can specify exactly where and how to connect. Start your Meteor server like this:
$ MONGO_URL=mongodb://user:password#localhost:27017/meteor meteor
You can also leave out the user:password# part of the command if no authentication is needed.
Scenario C: Connect to a second (3rd, etc) DB from the same Meteor app
Now we need to use MongoInternals.RemoteCollectionDriver. If you wish to use another database that is not the default DB defined upon starting the Meteor server you should use your approach.
var database = new MongoInternals.RemoteCollectionDriver('mongodb://user:password#localhost:27017/meteor');
var numberOfDocs = database.open('boxes').find().count();
Bonus: Why should you not use MongoInternals with Mongo.Collection?
As the docs indicate you should not pass any Mongo connection to the new Mongo.Collection() command, but only a connection to another Meteor instance. That means, if you use DDP.connect to connect to a different server you can use your code - but you shouldn't mix the MongoInternals with Mongo.Collection - they don't work well together.
Based on feedback from saimeunt in the comments above, s/he pointed out that MongoInternals is unavailable to the client portion of a Meteor app. Therefore, the solution was to add in the line "Boxes = new Mongo.Collection("boxes");" to the client logic - here was the final working solution:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js
if (Meteor.isClient) {
Boxes = new Mongo.Collection("boxes");
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
Meteor has 2 different environment : the server environment running on Node.JS and the client environment running in browsers.
In your code you declare the Boxes Mongo collection only in the server environment, you need to take this declaration out of the Meteor.isServer condition (and BTW don't use these, separate your code in server/, client/ and lib/ directories).
Also, not sure if you need to connect to your MongoDB this way, maybe you should look into the MONGO_URL environment variable it probably already does what you need ? (provide a mongo connection URL to a distant (or local) Mongo server).