要创建一个基于 **MongoDB Stitch** 的 To-do App 后端,需注意:**MongoDB Stitch 已于 2021 年正式弃用并整合进 MongoDB Realm

张开发
2026/6/11 12:59:36 15 分钟阅读
要创建一个基于 **MongoDB Stitch** 的 To-do App 后端,需注意:**MongoDB Stitch 已于 2021 年正式弃用并整合进 MongoDB Realm
要创建一个基于MongoDB Stitch的 To-do App 后端需注意MongoDB Stitch 已于 2021 年正式弃用并整合进 MongoDB Realm现统称 MongoDB Developer Data Platform。因此当前推荐使用MongoDB Realm现为 Atlas App Services构建安全、无服务器的 To-do App 后端。以下是关键步骤概览基于最新 Atlas App Services✅ 1. 创建 MongoDB Atlas 项目与集群登录 cloud.mongodb.com创建免费 Atlas 集群e.g., M0在数据库中创建集合todos如todoApp.todos✅ 2. 启用 Atlas App Services原 Realm进入项目 → “App Services” → “Build New App”关联已创建的 Atlas cluster设置应用名称e.g.,todo-app-backend✅ 3. 配置数据访问规则Rules在todoApp.todos集合上设置灵活权限例如{rule:{read:{owner_id:%%user.id},write:{owner_id:%%user.id}}}实现用户数据隔离需在客户端写入owner_id: %%user.id✅ 4. 启用 Authentication认证开启 Email/Password 或 Google 登录可选配置匿名登录用于快速原型✅ 5. 可选定义 GraphQL API 或 REST API自动暴露 CRUD 操作通过 Rules 控制或自定义 Function如addTodo用 JS 编写业务逻辑✅ 6. 客户端集成示例Web / Reactimport{Stitch,RemoteMongoClient}frommongodb-stitch-web-sdk;// ⚠️注意此 SDK 已过时// ✅ 正确方式2024import{StitchAppClient,AnonymousCredential,UserPasswordCredential}frommongodb-js/stitch-browser-sdk;// ✅ 推荐使用 mongodb-js/stitch-browser-sdk兼容 Realm// 或更现代使用 mongodb-js/atlas-app-services官方新 SDKconstclientStitchAppClient.initializeApp(your-app-id);awaitclient.auth.loginWithCredential(newAnonymousCredential());constmongodbclient.service(mongodb-atlas);consttodosmongodb.db(todoApp).collection(todos);// 添加待办awaittodos.insertOne({text:Learn Atlas App Services,completed:false,owner_id:client.auth.currentUser.id,createdAt:newDate()}); 补充说明所有网络请求由 Atlas App Services 自动处理身份验证、数据过滤与 HTTPS 加密无需管理服务器、API 网关或 JWT 签发逻辑支持实时订阅collection.watch()、同步Device Sync等高级功能按需启用如需完整可运行代码含前端 后端规则 部署指南可进一步说明技术栈React/Vue/Flutter是否需要 TypeScript是否需离线支持To-do App: Create a Stitch Backend¶MongoDB LogoServerDriversCloudToolsGuidesGet MongoDBClose ×MongoDB StitchIntroduction Tutorials Overview Basic Blog Tutorial Blog App Overview Build the Blog Backend Build a Web-based Blog Client To-Do App Tutorial To-do App Overview Build the To-do Backend Build a To-do Client Add Google Authentication Add Facebook Authentication Add Collection-Level Watch Users Authentication MongoDB Atlas GraphQL MongoDB Mobile Functions Triggers External Services Values Secrets Application Deployment Hosting Troubleshooting Stitch Administration Application Logs Client SDKs Release Notes Stitch Tutorials To-Do App TutorialTo-do App: Create a Stitch BackendAuthor: Stitch Documentation TeamWhen completed, you will have built a Stitch backend app that handles the basic requirements of a To-do app.Time required: 15 minutesWhat You’ll NeedThere are no prerequisites for this guide.ProcedureA. Create a MongoDB Stitch AppEstimated Time to Complete: ~8 minutes1Log into Atlas.To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.2Create an Atlas cluster.If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.Atlas provides a Free Tier M0 replica set as well as paid M10 clusters. Free Tier deployments have restrictions as compared to paid M10 deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier), M2, and M5 Limitations.3Add a MongoDB Stitch application.In Atlas, click Stitch Apps in the left-hand navigation. Click the Create New Application button. Under Application Name, enter a name for your application. The name can only contain ASCII letters, numbers, underscores, and hyphens. Under Link To Cluster, select the MongoDB Atlas cluster that you’d like to use for your application. Click Create.After you click Create, a new Stitch application will be created for you. The application will include a MongoDB service named mongodb-atlas that is linked to your cluster. This process may take several minutes.Once your application has been created, you will be automatically redirected to the Stitch application console.B. Define a Rule and Create a SchemaEstimated Time to Complete: ~6 minutesMongoDB Stitch rules specify the read and write access for the fields in your collections. Schemas define the shape of the data in your collections.1Create a namespace for the todo.items collectionIn the left navigation pane, under MongoDB Clusters, click Rules. Next to your Atlas service name (typically mongodb-atlas), click the plus button. In the Add New Collection screen, provide the following values: Property Value Database Name todo Collection Name items Select a Template Users can only read and write their own data Field Name For User ID owner_id Stitch creates a new rule (a combination of a role and permissions) based on the template. This rule allows an authenticated user to only read and write their own documents and to insert new documents. Click Add Collection.MongoDB AuthorizationMongoDB Stitch rules do not override the read and write access (i.e. authorization) that may have been set up separately in MongoDB. That is, MongoDB Stitch rules determine whether the fields are readable or writable; not whether the client has authorization to read or write to a particular database or collection.Similarly, MongoDB Stitch validation rules do not override document validation rules set up separately in MongoDB.To view the rule associated with the template, expand todo, and then click on items. Click on the edit button ( pencil icon ) to open the role editor.By default, the collection has the following Apply When rule:{“owner_id”: “%%user.id”}With this rule, read and write operations can access all fields in a document if the document contains an owner_id field whose value equals the user ID (%%user.id) of the client issuing the read. If the owner_id field in the document does not equal the client user id, the document is not readable.2Add a Schema for todo.items.ImportantThis step is only necessary if you’re using GraphQL to query your data. GraphQL requires a database schema to structure queries and mutations. Creating a schema will not impact your MongoDB queries if you are following the Web, Android, or iOS tutorials.A schema is a JSON document that defines the shape and contents of your collection. Stitch allows you to generate a schema based on the data in your collection or create one manually. Since we don’t have any data in our todo collection yet, we’ll choose the second option.To add a new schema, click on the Schema tab. Paste the following schema into the Stitch Schema text box:{“title”: “item”,“properties”: {“_id”: {“bsonType”: “objectId”},“owner_id”: {“bsonType”: “string”},“task”: {“bsonType”: “string”},“checked”: {“bsonType”: “boolean”}}}The schema defines the shape of the data in the todo collection. Each item in the collection has four fields: _id, owner_id, task, and checked. We also define the types for each of these fields.After you paste the schema into the text box, click Save on the top right corner.How Stitch uses your SchemaAlthough MongoDB collections do not require a schema to be specified, Stitch can use schemas to enforce the shape of the data in your collection. When a schema is enforced, users will receive an error if they attempt to insert or update documents that do not match the fields and types in the schema.Stitch requires a schema be defined when you use GraphQL in your application. The GraphQL query language uses your schema to create query and mutation functions.You can view the GraphQL operations generated from your schema by clicking GraphQL under Data Access Security in the left-hand navigation bar. The Documentation Explorer on the right-hand side shows all the GraphQL operations you can execute based on your collection schema. Click Query under Root Types to view the generated queries:item(query: ItemQueryInput): Itemitems(query: ItemQueryInputsortBy: ItemSortByInputlimit: Int): [Item]!The item function takes in an ItemQueryInput and returns an Item; this is similar to the findOne method that finds one document. items works similarly, but returns an Item array. GraphQL generates similar functions for inserting, updating, and deleting documents in your collection called mutatations.C. Set Up AuthenticationEstimated Time to Complete: ~1 minuteTo get started, we’ll use only anonymous authentication. This allows a user to load your app and try it out, but as soon as they are done using the app, they will no longer be able to access their to-do list. We will add additional authentication providers – and the ability to link accounts – later.To enable Anonymous Authentication:In the left-hand navigation, under Data Access Security, select Users. Select the Providers tab. In the authentication provider list, click the row that is labeled Allow users to log on anonymously. Click the Disabled slider so that it turns green and changes to Enabled. Click Save.D. Deploy Your ApplicationEstimated Time to Complete: ~1 minuteStitch saves changes that you make in a draft state that is not immediately available to client applications. To give client applications access, you must deploy your draft changes. To deploy changes, click Review Deploy Changes in the banner at the top of the Stitch UI and then click Deploy.SummaryCongratulations! You have set up and deployed the Stitch backend app and are now ready to build a client application.What’s NextNow it’s time to build one or more client To-do applications. Follow this tutorial to build the client of your choice.← To-do App Overview Build the To-Do Client →

更多文章