如何将MongoDB Orders集合文档分配至多个Realm?
Absolutely, this is totally feasible with MongoDB Realm! Here's a step-by-step solution to make a single orders document accessible to both a customer-specific and merchant-specific Realm instance:
Solution Overview
We'll use Flexible Sync (Realm's query-based synchronization) combined with role-based permissions. This lets the same orders document sync to multiple Realm instances as long as it matches each instance's subscription query.
Step 1: Enable Flexible Sync
First, head to your Realm App dashboard and enable Flexible Sync for your orders collection. This replaces the older partition-based sync and lets you sync documents based on dynamic queries instead of a single partition key.
Step 2: Define Your Orders Schema
Make sure your orders collection schema includes the required fields. For example, in Realm's schema editor:
{ "title": "Order", "properties": { "_id": { "bsonType": "objectId" }, "merchantId": { "bsonType": "string" }, "customerId": { "bsonType": "string" }, // Add other order fields (e.g., total, items, status) here }, "required": ["_id", "merchantId", "customerId"] }
Step 3: Configure Role-Based Permissions
Set up permissions so customers can only access their own orders, and merchants can only access orders linked to their ID. Go to the "Rules" section in your Realm App and update the orders collection rules:
For Customer Roles
{ "read": "resource.data.customerId == user.id", "write": "resource.data.customerId == user.id" // Adjust if customers shouldn't modify orders }
For Merchant Roles
{ "read": "resource.data.merchantId == user.id", "write": "resource.data.merchantId == user.id" // Adjust if merchants have specific write access }
Step 4: Set Up Client-Side Subscriptions
On the client side, create subscriptions that filter orders based on the current user's ID. This tells Realm which documents to sync to the local instance.
Example (Swift)
Customer's Realm Instance
guard let currentUser = app.currentUser else { fatalError("No logged-in user") } let realmConfig = currentUser.configuration(partitionValue: "") // Empty for Flexible Sync let realm = try! Realm(configuration: realmConfig) // Subscribe to orders where customerId matches the current user try! realm.subscriptions.update { subs in subs.append(QuerySubscription<Order>(name: "My Orders") { $0.customerId == currentUser.id }) } // Access synced orders let myOrders = realm.objects(Order.self)
Merchant's Realm Instance
guard let currentUser = app.currentUser else { fatalError("No logged-in user") } let realmConfig = currentUser.configuration(partitionValue: "") let realm = try! Realm(configuration: realmConfig) // Subscribe to orders where merchantId matches the current user try! realm.subscriptions.update { subs in subs.append(QuerySubscription<Order>(name: "Merchant Orders") { $0.merchantId == currentUser.id }) } // Access synced orders let merchantOrders = realm.objects(Order.self)
Example (JavaScript)
Customer's Realm Instance
const app = new Realm.App({ id: "YOUR_APP_ID" }); const currentUser = app.currentUser; const realm = await Realm.open({ schema: [OrderSchema], sync: { user: currentUser, flexible: true, }, }); await realm.subscriptions.update((mutableSubs) => { mutableSubs.add( realm.objects("Order").filtered("customerId == $0", currentUser.id) ); }); const myOrders = realm.objects("Order");
Merchant's Realm Instance
const app = new Realm.App({ id: "YOUR_APP_ID" }); const currentUser = app.currentUser; const realm = await Realm.open({ schema: [OrderSchema], sync: { user: currentUser, flexible: true, }, }); await realm.subscriptions.update((mutableSubs) => { mutableSubs.add( realm.objects("Order").filtered("merchantId == $0", currentUser.id) ); }); const merchantOrders = realm.objects("Order");
Key Notes
- Any changes to the order document (e.g., status updates from the merchant) will sync automatically to both the customer's and merchant's local Realm instances.
- Flexible Sync is ideal here because it doesn't restrict documents to a single partition—instead, it syncs any document that matches the active subscription queries.
- Make sure your user roles are correctly assigned (e.g., tag customer users with a "customer" role and merchant users with a "merchant" role) so the permissions apply as expected.
内容的提问来源于stack exchange,提问作者Surender Nandal

