Connect to MongoDB Atlas Cluster db with react-native app - javascript

I'm having a hard time understanding how to connect to the MongoDB Atlas Cluster from my react-native app. What I'm trying to do is basically take my data from my component login page (userName and password) and connect to the Atlas Cluster db to see if the data is there.
Im using React Native and use Expo to create the app. My login page opens up and I put in the data.
I want to take that data and then use the following code (from the Atlas Site Connection String) to connect and check.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<userName>:<password>#testcluster1-dbdq3.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Since react-native establishes a server, do I need to involve Express? Im new to this so I'm still trying to figure out what packages to utilize. Should I also install mongoose or mongoDB or both (from NPM). Im trying to wrap my head around how this works from a basic perspective and the packages required.
I want to perform a check against my userID and PW from my login page to the DB to see if the user exists. If the user doesnt, then I'll have them fill out some info and register which means writing a new user to my db.
So basically, I need to understand the code logic for:
Connecting to the db through my app and when to perform this
connection (when app loads or each time the login button is clicked)
Take data from my userName and password and search the atlas db to
see if the user exists. If so, then the next page loads.
If username and password doesn't exist, then I write the new user
and password to the db.
Thanks

I think you should rewrite the code following the format suggested by mongodb here:
https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
So essentially:
const MongoClient = require('mongodb').MongoClient;
//make sure to check connection string is correct here, since this depends on the whether you are running standalone, replica, sharded cluster
const uri = "mongodb+srv://<userName>:<password>#testcluster1-dbdq3.mongodb.net/test?retryWrites=true&w=majority";
MongoClient.connect(uri, { useNewUrlParser: true }, function(err, client) {
if (err) {
//error
} else {
var collection = client.db('test').collection('devices');
//client.close() should be called after you are done performing actions such as collection.update, etc.
}
});

you can use any npm package with Expo if it works with RN (React Native), but you may need to detach in order to do so. Any npm packages which include native iOS or Android code will not work with Expo out of the box, unfortunately. Because MongoDB NPM package just mentioned the Node.js in thier docs, this doesn't mean that it will work on React Native. That's why MongoDB made this page about JUST React Native https://docs.mongodb.com/realm/tutorial/react-native/
You may need to use Realm Package to connect to MongoDB with React Native.

Related

Strapi + Hashicorp Vault Dynamic Database Secret

I have implemented a script and a cron task in strapi to generate new database secret from my vault server.
const client = new VaultEnv()
const secret = await client.secretManager()
strapi.config.set('database.connection.connection.user', secret.data.username)
strapi.config.set('database.connection.connection.password', secret.data.password)
So far the above code block only works at start-up in the register({ strapi }) function at src/index.js, but after in cron task it updates the connection config but strapi seems to only use the config that was set at register({ strapi }) function at start-up
I have also tried injecting into process.env but still the same result or I probably did it the wrong way.
Apparently it may be impossible but I will leave this question open in-case there are others searching.
A workaround will be to take advantage of container orchestration to restart strapi servers (agents) for zero downtime.

How to connect MySQL database to ReactJS app?

I have build a Todo App with create-react-app. The store I'm using is based on Local Storage(JS attribute of object window). Now I created a MySQL databases and want to connect to that database, so the state will show the values from database, and will be updated through actions.
I've tried to connect to db and output values through 'node' console using db.js. It works.
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: 'root'
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM tasks", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Is it possible to connect the state of app to database using this script?
You can't connect them directly.
JavaScript running in a web browser cannot speak the MySQL protocol (nor can it make raw network connections that would be needed to write an implementation in JS).
Instead, create a web service (in the programming language of your choice, which could be JavaScript running on Node.js (e.g. the code you have already + Express.js + some glue)) and use Ajax to communicate with it.
The general solution for a question like this is the following framework:
Back-end (Node.js, Express, Database connection including authorization)
Front-end (React(, Redux to manage state))
If you then launch the React app, it should populate its state based on data retrieved from the database, which is a process to which you can add authorization (make retrievable data depend on the role/status of the user).
In the back-end you can define functions that take in a certain subset of parameters, which performs database actions, to which you can add business rules for your application. The React app then just sends HTTP requests to the Express server, which handles everything that needs verification and authorization before even touching the data.
If you search the internet for any configuration of a fullstack architecture using React and MySQL, you'll find similar results to what I mentioned.

Simple connection to mongodb in react app

I have created simple react app using 'create-react-app'. This app contains form, validation and bootstrap things. Nothing fancy yet works like a charm.
I have also signed up to mongo to get a free cluster so I can send over some data to. So I have this URL:
mongodb+srv://matt:passwprd#cluster0-jlasm.mongodb.net/test
Now, all I want to do is to send JSON data from the form to mongo but I don't know how.
When I am following tutorials and installing MongoDB, mongoose or whatever packages and adding basic setup for future CRUD operations:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
The entire application crashes:
./node_modules/mongodb-core/lib/uri_parser.js
Module not found: Can't resolve 'dns' in 'C:\Users\Mateusz\Desktop\brainhub\node_modules\mongodb-core\lib'
I used to send data using jQuery or mysql_query in PHP but I can't overcome this problem. In other words I want to achieve functionality like presented in this video: https://www.youtube.com/watch?v=Jsqz5op4fH8 So as I said, simple data update.
My suspicion is that react-scripts server listener has some sort of conflict with mongo but I am not sure.
Please help me because I am loosing my nerves.
You are using node.js so start server app try using express routing here is a link to a tutorial https://zellwk.com/blog/crud-express-mongodb or https://codeburst.io/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 or try doing a google search(node.js mongodb and express).
Then when returning a request from server send the data required then use your react client to handle the data recived
Hope it works!
handleSubmit(){
let databody = {
"name": this.state.name,
// Remaining form Data
}
return fetch('mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
// Form Fields
<input type="submit" value="Save" />
</form>
</div>
);
}
To connect to MongoDb in javascript, you must use a node.js server.
It is therefore impossible to directly connect your React application to your MongoDb cluster.
For more information, visit the official MongoDb documentation
First you need to create a React.js on the frontend and then node.js on the backend web application.
Then, you need to connect your mongodb collection to your Node.js server.
Then you can send your form data to your node.js server and your node.js server will send your form data to your mongodb collection.
Making a full-stack React-NodeJS-MongoDB web application can be a little challenging, if you do not know NodeJS. So you might first start with EJS-NodeJS-MongoDB web application. But in any case, here are links for your question:
https://www.youtube.com/watch?v=3isCTSUdXaQ&t=2248s
https://www.youtube.com/watch?v=Oa0pMn0tvU4&t=1316s

sync data from mongoDB to firebase and vice-versa

My current situation:
I have created an application using React, NodeJS and Electron. Most of the users are a kind of offline users. They use my application offline.
Next plans:
Now, I am planning to create a mobile application for them. I plan to create that application using React-Native.
Since their database is offline, I planned to give them a sync to firebase button in desktop application. When he clicks on sync to firebase button, the data in their local mongodb should syncronize with firebase.
My thoughts:
when a new record is added to mongodb, I will store a new key with that record which will look like: new: true.
when a record is updated I will store a key named updated: true
similarly for delete...
And then when user presses Sync to firebase, I will search for those records and add/update/delete respective records on firebase and then I will remove those keys from mongodb database.
Problems in executing my thoughts:
At first it does not smell me a good thing as I think it is time consuming because I will perform operations on firebase as well as mongodb.
Another problem with this approach is that if I think the other way round, that when user add/update/delete a record from React-Native app, firebase will have those keys line new/updated/deleted and then when user presses sync button in desktop application, I will have to do same thing but in reverse.
Yet another problem is that if user accidently uninstalled my application and then reinstalls it, then what should I do?
And the biggest problem is managing all the things.
My Expectations:
So, I want a clean and maintainable approach. Does any one have any idea on how to sync data from mongodb to firebase and vice-versa?
Both database systems supports for some sort of operation log or trigger system. You can use these to live update changes to databases to sync them almost real time.
For MongoDB
You can use Oplog to see what changes made to database (insert/update/delete) and run a suitable function to sync firebase.
oplog
A capped collection that stores an ordered history of logical writes
to a MongoDB database. The oplog is the basic mechanism enabling
replication in MongoDB.
There are small libraries that help you easily subscribe to these events.
Example (mongo-oplog)
import MongoOplog from 'mongo-oplog'
const oplog = MongoOplog('mongodb://127.0.0.1:27017/local', { ns: 'test.posts' })
oplog.tail();
oplog.on('op', data => {
console.log(data);
});
oplog.on('insert', doc => {
console.log(doc);
});
oplog.on('update', doc => {
console.log(doc);
});
oplog.on('delete', doc => {
console.log(doc.o._id);
});
For Firebase
You can use Cloud Functions. With Cloud Functions you can watch triggers like Cloud Firestore Triggers or Realtime Database Triggers and run a function to sync MongoDB database.
With Cloud Functions, you can handle events in the Firebase Realtime
Database with no need to update client code. Cloud Functions lets you
run database operations with full administrative privileges, and
ensures that each change to the database is processed individually.
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onWrite((event) => {
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
});

MongoDB security, what am I missing?

If you wanted to push something live with Node JS, Mongo DB & Express does this suffice as a secure way to connect to the Mongo DB?
Can someone explain this code from a security perspective?
===
Alot of tutorials simply use...
var mongoClient = new MongoClient(new Server('localhost', 27017));
Mongos Documenation includes...
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
===
Code is based on Mongo Documentation - http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html#getting-that-connection-to-the-database
You're not missing much. The best thing to do with most database servers is to secure them by keeping them away from the public network.
The same is true of e.g. MySQL--it lacks enterprise authentication methods like Kerberos (requested since 2004: http://bugs.mysql.com/bug.php?id=6733).
You just need to keep your DB server inside the trusted LAN. If you want to use a login with password, it's better than nothing, but exposing most databases to the outside world is a bad idea, because they lack simple protections like bad-password rate limiting. They're just not meant to be user-facing in that way.

Categories