Introduction
MongoDB Realm is a data-driven development platform for modern apps. It has a serverless backend that makes it simple to not only publish and read data, but also to authenticate users, maintain data synchronised across numerous devices, and more.
In this tutorial, we’ll learn how to create a MongoDB Realm functions and then use them in our React Native application.
We’ll create an app to show e-commerce products by fetching data from mongo database with the help of realm functions.
Create a MongoDB Realm App
Create a MongoDB Cluster
We need to go through a few steps to establish a MongoDB Realm app, the first of which is to create a MongoDB Cluster. Go to the MongoDB portal to get started. Create an account if you don’t already have one, and then log in to continue.
If you’re not redirected to the Projects page, click on the logo at the top left to get redirected.
Once you’re on the Projects page, click on the “New Project” button at the right.
Then you will be asked to enter a project name. You can enter any name of your wish.
After that, you’ll be asked to add members, you can add members if you want or can leave it blank and proceed further by clicking on “Create Project”.
Once the project is created, you will be redirected to the database section , here you need to click on “Build a database”.
After you click on that you will see a couple of options regarding your cluster plan. For this tutorial, you can just choose the free plan and continue.
Then after that, you can just click on “Create”. Moving next you will find some settings regarding the cluster you can leave them as they are and proceed by clicking on “Create Cluster”.
After this, your cluster will take some time to deploy. You need to wait until it’s created and deployed, which can take a couple of minutes.
Creating the realm application
The next step will be to create a realm application head over to the realm portal and there will be a welcome screen pop up.
MongoDB realm gives us many pre-configured templates, each of which has some project-specific options. For this tutorial, we’ll select the “Build Your Own App” option and customise our settings.
A dialog box will show to start creating MongoDB Realm App. You’ll need to enter a name for the Realm Application which can be whatever you want. Then, you’ll need to choose a cluster to link the Realm App to. Choose the cluster we just created. Once you do that, click on “Create Realm Application” which will be below.
Now we have our application created and we are ready to add data to our database. Head back to the atlas and select database. There you will find an option labelled with add my own data.
On clicking, you will see a pop up to create a database. Enter any name for the database and collection but make sure to note it as we will require it later for making a request to our database.
Inserting Data in our cluster
The next step will be to add e-commerce data to our Cluster. You can add your own data or else you can use this link to get data.
Click on “insert document” to the right to start inserting data.
Then enter the JSON data you have in the insert box.
Now we have our dataset ready which we will retrieve using realm functions. Before creating realm functions we need to define rules and schema for our data.
Click on the realm tab and select the rules option in your left sidebar. You will see a section to configure your collection. Select the collection which you previously made if it is not visible click the database name to make it visible.
For our collection, we’ll need to choose a permission template. The permission template determines who can read and write to the collection’s data. We don’t need to write data to the database, and we’ll make the function system function anyhow, so selecting no template is a good choice. To configure the collection, click the “Configure Collection” option.
You must deploy the Realm App every time you make changes to it for the changes to take effect. Click “Review Draft & Deploy” under the blue banner at the top to deploy the modifications we just made.
As a result, the changes we had just made were saved. We created a Realm App that communicates with our cluster and its collections. This will offer us a serverless backend that will make it simple to access data from our cluster.
We need to create Schema definitions for each of our collections and documents in order to query them. To do so, go to the sidebar and select Schema.
Then, click on Generate Schema button. This will generate the schema based on the data that’s already in the collection.
Choose the collection name we created under “Choose Schemas” and “20” for Sample type because our data is simple and we don’t need to sample many documents.
Once it’s done, you’ll see the Schema generated with all the fields and their respective types.
If you are using the data provided above you will get an schema similar to this.
Setup Authentication in Realm App
In our Realm app, we’ll be using Email & Password authentication which means users have to log in with email and password to retrieve the data.
In the Realm Portal, click on Authentication in the sidebar. You’ll see a few Authentication providers that are all disabled.
“Email/password” will be enabled. Toggle it on by clicking the edit button for this one. To begin, turn on the provider. Choose “Automatically confirm users” for “User Confirmation Method.”
The “Password Reset Method” is the next step. Your users can also reset their passwords using MongoDB Realm. We won’t be using it, but if we need to configure it, just type http://example.com/ in the “Password Reset URL” field.
The options will be similar to these after this click on save the draft and then click on the review draft and deploy option to the top.
Now we are ready to add our user for authentication. Click on add new user button to add users.
Add any email address and password once entered click on create to proceed.
This completes our setup for authentication. We will need the email and password to make the connection to our realm backend from our react native app. Click on review draft and deploy to update the changes.
Creating realm functions
Now we will create our own serverless functions to fetch data from our database.
Click on functions to your left sidebar and then select “Create New Function” to make new functions.
Add the function name and select system for authentication . switch to function editor to write the logic for functions.
exports = function (arg) {
var collection = context.services
.get(“mongodb-atlas”)
.db(“Your_Database”)
.collection(“Your_Collection”);
return collection.find({});
};
Replace the database and collection keyword in the function with your respective saved database and collection.
Click on run to the bottom right to check the working of the function. If you get some error that means you have done something wrong please recheck with all the above steps to make it work.
Once you can see data in the result section you are good to go. Click on save draft to the right to save.
One last thing to do is make sure to click on Review Draft & Deploy for all the changes to take effect.
Now, we have our MongoDB Realm app ready for integration with React native. Next, we’ll go over how to integrate it with React and use the serverless function we’ve been setting up.
React Native Setup
In case you don’t have a React native project ready, run the following to create one:
npx react-native init EcoShop
cd EcoShop
Next, we’ll install the MongoDB Realm SDK:
Yarn add realm
cd ios && pod install
We will also install cocaopods by running pod install in ios directory.
We’ll keep things basic with a text that says Get products, and when you click it, our serverless functions will perform a request and display the fetched goods.
Let’s go over how to connect to Realm Apps first. You first need an App ID. You’ll find the App ID on the Dashboard of your realm app.
Firstly create a js file name env.js for storing our email, password and app id.
const username = “Your app user email”;
const password = “Your app user password”;
const id = “Your app id”;
export { username, password, id };
Then open the app.js file and delete old code and enter the below code.
import React, { useEffect, useState } from “react”;
import { Text, SafeAreaView, StyleSheet } from “react-native”;
import { ScrollView } from “react-native-gesture-handler”;
import Realm from “realm”;
import { username, password, id } from “./env”;
import ProductItem from “./ProductItem”;
export default function App() {
const [user, setUser] = useState(null);
const [products, setProducts] = useState(null);
const getUser = async () => {
const app = new Realm.App({ id: id });
const credentials = Realm.Credentials.emailPassword(username, password);
try {
const data = await app.logIn(credentials);
setUser(data);
} catch (err) {
console.error(“Failed to log in”, err);
}
};
const fetchProducts = async () => {
const data = await user.functions.FetchData();
setProducts(data);
};
useEffect(() => {
getUser();
}, []);
return (
< SafeAreaView style={styles.main}>
< ScrollView>
{products ? (
products.map((item: any) => {
return < ProductItem key={item.id} item={item} />;
})
) : (
< Text style={styles.text} onPress={fetchProducts}>
Get Products
< /Text>
)}
< /ScrollView>
< /SafeAreaView>
);
}
const styles = StyleSheet.create({
text: {
fontSize: 24,
marginTop: 200,
},
main: {
flex: 1,
justifyContent: “center”,
alignItems: “center”,
},
});
We have two states here to hold our user info as well as the things we’ll be receiving. We first call the realm backend with our email, password, and app id to collect the user info. This call is made in useEffect, which is the first to be called. The user data is saved in the user state.
We have a conditional statement in the UI that shows the text when the product state is null and the product when it isn’t. We have another function called fetchProducts that retrieves e-commerce data using the user data we have.
Now creating the component for the products. Create a js file named ProductItem.js
import React, { FC } from “react”;
import { View, Text, StyleSheet, Image, Dimensions } from “react-native”;
import { Ionicons } from “@expo/vector-icons”;
const { width, height } = Dimensions.get(“screen”);
const ProductItem = ({ item }) => {
const { image, price, rating, title, description } = item;
const rate = rating.rate;
const arr = new Array();
for (let i = 1; i <= 5; i++) {
if (i <= Math.ceil(rate)) arr.push(1);
else arr.push(0);
}
return (
< View style={styles.container}>
< View style={styles.ImageContainer}>
< Image
resizeMode=”contain”
style={styles.image}
source={{
uri: image,
}}
/>
< /View>
< View style={styles.infoContainer}>
< Text style={styles.title}>{title}< /Text>
< View style={styles.rating}>
{arr.map((item, index) => {
return (
< Ionicons
key={index}
name={item == 1 ? “star” : “star-outline”}
color={“orange”}
size={20}
style={{ marginLeft: 1 }}
tvParallaxProperties
/>
);
})}
< Text style={styles.ratingCount}>{rating.count}< /Text>
< /View>
< Text style={styles.price}>{`Rs ${price}`}< /Text>
< Text numberOfLines={4} style={styles.desc}>
{description}
< /Text>
< /View>
< /View>
);
};
const styles = StyleSheet.create({
container: {
width: width,
height: height * 0.25,
backgroundColor: “white”,
flexDirection: “row”,
borderWidth: 1,
borderColor: “#f2f2f2”,
},
image: {
width: width * 0.3,
height: height * 0.2,
},
rating: {
flexDirection: “row”,
alignItems: “flex-end”,
justifyContent: “flex-start”,
marginTop: height * 0.005,
},
ImageContainer: {
justifyContent: “center”,
alignItems: “center”,
width: width * 0.4,
backgroundColor: “white”,
},
infoContainer: {
justifyContent: “flex-start”,
width: width * 0.6,
marginVertical: height * 0.01,
padding: width * 0.03,
},
title: {
fontSize: width * 0.04,
fontWeight: “500”,
},
ratingCount: {
marginLeft: width * 0.02,
fontWeight: “400”,
fontSize: width * 0.035,
},
price: {
fontSize: width * 0.04,
fontWeight: “500”,
marginTop: height * 0.01,
},
desc: {,
fontSize: width * 0.038,,
fontWeight: “400”,,
marginVertical: height * 0.01,,
},
});
export default ProductItem;
This completes our coding part for the app. Let us check our app now.
Run the following command to compile the app and run in device :
yarn ios
OR
yarn android
As we can see our app is working and we are able to successfully fetch the data from our database.
Conclusion
We learned how to leverage realm serverless functions and integrate them into our react native app in this tutorial. We were able to create a simple app that retrieves and displays data from our realm backend.