Establish a connection between a react-native app and a MongoDB Atlas cluster database

I'm struggling to grasp the concept of connecting my React Native app to the MongoDB Atlas Cluster. Essentially, I want to retrieve user data (username and password) from a login component page and verify its existence within the Atlas Cluster database.

Currently, my app is built using React Native with Expo. The login page functions as expected, allowing users to input their credentials.

The objective is to utilize the provided code snippet (obtained from the Atlas documentation on Connection Strings) to establish a connection and perform the necessary checks:

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");
  // actions performed on the collection object
  client.close();
});

Considering that React Native sets up a server, I am uncertain if Express needs to be implemented. As a novice in this area, I am exploring suitable packages such as mongoose or MongoDB (from NPM). Understanding the fundamental logic behind these components and required packages remains crucial.

The primary goal is to validate the user ID and password against the database when logging in. If the entry does not exist, an option for registration will prompt the user to provide additional information - subsequently, adding a new user to the database.

Essentially, I aim to comprehend the following aspects regarding the code structure:

  1. The process of establishing a connection to the database within the application and determining when this connection should occur (upon app launch or upon clicking the login button).
  2. Retrieval of username and password data to conduct a search within the Atlas database for user verification. Upon successful validation, the subsequent page should load.
  3. In cases where the provided username and password do not match any existing records, the procedure involves writing the new user's credentials to the database.

Your guidance on these matters would be greatly appreciated.

Answer ā„–1

If you're looking to enhance your code, I suggest following the format recommended by mongodb which can be found here:

https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

In summary, your code should look something like this:

    const MongoClient = require('mongodb').MongoClient;

    //Ensure that your connection string is accurate depending on whether you are using a standalone, replica, or 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) {

             //Handle error

       } else {

             var collection = client.db('test').collection('devices');

             //Remember to call client.close() after completing actions such as collection.update, etc.

       }
    });

Answer ā„–2

If you want to use any npm package with Expo, it should be compatible with React Native (RN). However, you might have to detach in order to make it work. Keep in mind that npm packages containing native iOS or Android code will not function properly with Expo by default. Just because the MongoDB NPM package mentions Node.js in its documentation doesn't guarantee compatibility with React Native. That's why MongoDB has created a specific page dedicated to using MongoDB with React Native here: https://docs.mongodb.com/realm/tutorial/react-native/

To establish a connection between MongoDB and React Native, consider utilizing the Realm Package.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transient Flash of a jQuery Dropdown Menu

I'm currently developing a jQuery/CSS dropdown menu for a website, and everything is functioning well except for one issue. When navigating between sub-menu items, the text color of the selected main menu item briefly changes because of the CSS border ...

Unable to click, but can only be activated by touchstart or mousedown

Is it possible to bind a 'click' event to a paragraph? Here is the function I am using: $(document).on('touchstart mousedown',"p span.text", function(e) { console.log('I was clicked'); *more code here* }); When I ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

Newly inserted JSON component remains invisible

I am currently using express.js to create an API. My mongoose is returning a JSON object and I need to append an element to each item in the result.docs. This is how I am attempting to achieve that: for(let a in result.docs) { result.docs[a].link ...

Implementing an OnChange Event for a Multi-Select Feature in a Vue.js Application

Here is the HTML code for my multi-select input: <select id="invitees_list1" class="form-select" multiple name="multi"> @foreach ($seatedTable->invitees as $invitee) <option> {{ $invitee ...

Updating multiple documents with various values in Mongoose can be achieved through a straightforward process

Is there a way to combine these two update queries into a single update query? // delete the user with (requestID) from friends await User.updateOne({ _id: id, }, { $pull: { friends: requestID } }) // delete the user with (id) from friends await U ...

How can you modify the encapsulation of a third-party component in an Angular application?

Utilizing AngularElements with native encapsulation allows bs4 components to be used in a bs3 project. For example: @Component({ selector: 'app-my-button', templateUrl: './my-button.component.html', encapsulation: ViewEncapsulati ...

How to pause a loop temporarily before proceeding with the next iteration

I am facing a challenge where I want to trigger two events simultaneously, but only one event should be allowed to continue at a time. If an event is already in progress, I need the ability to forcefully stop it and allow the other event to take control. S ...

The minDate feature in Gravity Forms is failing to disable dates in the past

Iā€™m attempting to prevent users from selecting past dates on the datepicker within Gravity Forms, but I've encountered issues such as console errors or the functionality not working properly... Initially, I attempted the following approach: gform.a ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Whenever I declare it, the onclick method is executed

I have been attempting to define an onclick method that would trigger a function to clear and reconstruct the display, revealing more detailed information about the clicked item. However, I am facing an issue where the assigned onclick method is executed i ...

Using MongoDB to store functions within an aggregation framework

I've been using the following query to retrieve data from my mongo-db: db.FetchedUrl.aggregate({ "$match": { "type": db.eval('echoFunction(\"news\")') } }) Here's the function stored in my database: db.system.js.sav ...

Guide on integrating angular-schema-form into an Ionic 2.0 project using typescript

Recently, I embarked on creating an app with Ionic from scratch and decided to integrate the framework. While I faced no issues executing the example on a webpage, I encountered difficulties when attempting to do so with Ionic. To kickstart the project, ...

Click on ng-click to sort through the blog entries

Currently, I am in the process of developing a blog utilizing AngularJS and JSON. Nearly everything is functioning as expected except for one particular filter item. As I am relatively new to Angular, it presents a bit of a challenge for me. The issue ari ...

Expand Menu Options (jQuery)

Currently facing a jQuery problem that I can't seem to figure out. I've set up a menu with submenu elements and want to toggle the content height by clicking on menu items. The issue arises when clicking on another item causes the content to coll ...

When the object contains multiple arrays, filter out the id and remove it when clicked

I am working with an object that contains multiple arrays and aiming to filter out the id of the item to be removed onClick. However, I have encountered an error while trying to implement this logic. The error message I received is filter is not a functio ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Setting up automatic live reloading and assets compiling using Webpack in a Drupal project: A step-by-step guide

I've successfully configured Webpack to compile Sass and JavaScript in my Drupal custom theme named amazon. The styles.scss and index.js files are compiled from the assets/scss/ and assets/js/ folders respectively, into styles.css and index.js in the ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

Issue with AMCharts: DateAxis on my XY graph unexpectedly zooms out to the year 1970 when stacked

Currently, I am attempting to display multiple processes throughout a single day on an AMChart XY axis. Everything seems to be functioning correctly initially, but as soon as I stack the data, the timeline unexpectedly zooms out all the way to 1970. Howev ...