I’m just starting out learning mongodb and following the official tutorial on YT and ran into an error when trying to connect and run a function.
This is my code:
"use client"
import { useEffect, useState } from 'react'
import * as Realm from "realm-web"
export default function Home() {
const [products, setProducts] = useState([]);
useEffect(()=>{
const FetchProducts = async()=>{
const REALM_APP_ID = "{myAppId}";
const app = new Realm.App({id:REALM_APP_ID});
const credentials = Realm.Credentials.anonymous();
try{
const user = await app.logIn(credentials);
const allProducts = await user.functions.getAllProducts();
setProducts(allProducts);
console.log(allProducts);
}catch(error){
console.log(error);
}
}
FetchProducts();
},[])
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{products && products.map(product =>(
<p key={product['_id']} className='text-gray-200'>{product['name']}</p>
))}
</main>
)
}
This code displays all the items within the YT tutorial but I am getting an error of:
Error: Request failed (POST https://us-east-1.aws.realm.mongodb.com/api/client/v2.0/app/products-pqfns/functions/call): function not found: 'getAllProducts' (status 404)
at MongoDBRealmError.fromRequestAndResponse (webpack-internal:///(:3000/app-client)/./node_modules/realm-web/dist/bundle.dom.es.js:2871:24)
at async Fetcher.fetch (webpack-internal:///(:3000/app-client)/./node_modules/realm-web/dist/bundle.dom.es.js:3034:23)
at async Fetcher.fetchJSON (webpack-internal:///(:3000/app-client)/./node_modules/realm-web/dist/bundle.dom.es.js:3051:26)
at async FetchProducts (webpack-internal:///(:3000/app-client)/./src/app/page.tsx:25:37)
Also getting a Post Error. Doesn’t anyone know what I’m doing wrong? Thanks.
PS- I have created the function getAllProducts()
within atlas
edit:
I expanded this error and it says this:
{error: "no matching rule found", error_code: "NoMatchingRuleFound",…}
2
Answers
Nothing was wrong with the code, to fix this issue I had to do a device sync which was not shown in the tutorial. This fixed my error and I am receiving the data.
Your passing a string instead of the actual Realm ID
Try saving your Realm ID to .env.local and then pass it directly to REALM_APP_ID as process.env.REALM_APP_ID instead of doing this "{myAppId}". It’s safer that way.
.env.local