Next.js+TS调用MongoDB Realm函数报错:POST请求失败及函数未找到
问题描述
我刚开始学习MongoDB,跟着YouTube官方教程操作,在尝试连接并运行函数时遇到错误。我的代码如下:
"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> ) }
这段代码在教程中可正常展示数据,但我遇到如下错误:
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)
展开错误后显示:
{error: "no matching rule found", error_code: "NoMatchingRuleFound",…}
我已在Atlas中创建getAllProducts()函数,请问哪里操作有误?
排查解决步骤
- 确认函数名称完全匹配:检查Atlas App Services中创建的函数名是否为
getAllProducts,注意大小写、拼写,Realm对函数名大小写敏感,不能有多余空格或符号。 - 检查函数是否已部署:创建函数后必须点击「Deploy」按钮发布,未部署的函数无法被外部调用。
- 验证匿名用户权限:代码使用匿名登录,需确保在App Services的「Authentication」模块开启匿名认证,同时在函数的「Permissions」设置中,给匿名用户分配
Can execute的调用权限。 - 核对App ID正确性:代码中的
REALM_APP_ID要和Atlas App Services里你的应用ID完全一致,注意替换占位符{myAppId}为实际ID,不要保留花括号。 - 检查函数部署区域:错误请求地址显示区域为
us-east-1,确认你的App Services应用部署区域与之匹配,若区域不一致可能导致无法找到函数。
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

