### JavaScript Quick Start for Node.js SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Example demonstrating the Node.js SDK Quick Start using JavaScript. This includes setting up and opening a Realm. ```javascript const Realm = require('realm'); // Define your object model const TaskSchema = { name: 'Task', properties: { _id: 'objectId', description: 'string', isComplete: { type: 'bool', default: false, }, }, primaryKey: '_id', }; // Open a local Realm Realm.open({ schema: [TaskSchema], }).then(realm => { console.log('Realm opened successfully'); // Close the Realm when done realm.close(); }).catch(error => { console.error('Failed to open Realm:', error); }); ``` -------------------------------- ### TypeScript Quick Start for Node.js SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Example demonstrating the Node.js SDK Quick Start using TypeScript. This includes setting up and opening a Realm. ```typescript import Realm from "realm"; // Define your object model const TaskSchema = { name: "Task", properties: { _id: "objectId", description: "string", isComplete: { type: "bool", default: false, }, }, primaryKey: "_id", }; // Open a local Realm const realm = await Realm.open({ schema: [TaskSchema], }); console.log("Realm opened successfully"); // Close the Realm when done realm.close(); ``` -------------------------------- ### Setup Realm for Examples - Swift Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/swift/crud/filter-data.txt Sets up an in-memory Realm instance for the examples. This code is necessary to initialize the Realm database before running queries. ```swift let realm = try! Realm(configuration: .init(inMemoryIdentifier: "MyInMemoryRealm")) // Add some sample data try! realm.write { let project1 = Project() project1.name = "Project Alpha" let task1 = Task() task1.name = "Implement feature X" task1.assignee = "Alice" task1.isComplete = false task1.priority = 10 task1.progressMinutes = 60 task1.labels.append("backend") task1.labels.append("feature") task1.ratings.append(5) task1.ratings.append(4) let task2 = Task() task2.name = "Fix bug Y" task2.assignee = "Bob" task2.isComplete = true task2.priority = 5 task2.progressMinutes = 120 task2.labels.append("bugfix") task2.ratings.append(3) let task3 = Task() task3.name = "Write documentation" task3.assignee = nil task3.isComplete = false task3.priority = 8 task3.progressMinutes = 30 task3.labels.append("docs") project1.tasks.append(objectsIn: [task1, task2, task3]) realm.add(project1) } ``` -------------------------------- ### Installation: Clean Build Bundle and Target Installation Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/test_sdk_example/linux/CMakeLists.txt Configures the installation process to start with a clean build bundle directory and installs the application executable to the specified prefix. ```cmake # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Get Project Packages Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/README.md Fetches all necessary packages for the example project. This command should be run after cloning the repository. ```sh dart pub get ``` -------------------------------- ### Clone LiveData Quick Start Repository Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/quick-starts/livedata.txt Clone the example repository from GitHub to get started with the LiveData quick start application. ```bash git clone https://github.com/mongodb-university/realm-android-livedata.git ``` -------------------------------- ### Add Device Sync to Quick Start with .NET SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md A line added to the Quick Start guide indicating that it demonstrates adding Device Sync using the .NET SDK. ```csharp // This Quick Start demonstrates adding Device Sync. // Configuration and usage details for Device Sync would follow. ``` -------------------------------- ### Add migration section with examples for SwiftUI Guide Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Add a migration section with examples to the SwiftUI Guide, demonstrating how to handle schema changes. ```swift // Example of a migration block: let config = Realm.Configuration( schemaVersion: 2, migrationBlock: { migration, oldSchemaVersion in if oldSchemaVersion < 1 { // Perform migration for schema version 1 } if oldSchemaVersion < 2 { // Perform migration for schema version 2 // e.g., add a new property migration.enumerate(MyObject.className()) { (oldObject, newObject) in newObject?["newProperty"] = "default value" } } } ) let realm = try! Realm(configuration: config) ``` -------------------------------- ### Complete Local Realm Example (Kotlin) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/quick-starts/quick-start-local.txt A comprehensive Kotlin example demonstrating the setup and usage of local Realm data, including object definition, creation, and modification. ```kotlin package com.mongodb.realm.realm-java-quickstart import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import io.realm.Realm import io.realm.RealmObject import io.realm.annotations.PrimaryKey import org.bson.types.ObjectId // Define the Task object model class Task(@PrimaryKey var _id: ObjectId = ObjectId(), var name: String = "", var isComplete: Boolean = false, var owner: String? = null) : RealmObject() // Define the TaskStatus object model class TaskStatus(var name: String = "") : RealmObject() class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Use Realm.getDefaultInstance() to get a Realm instance val realm = Realm.getDefaultInstance() // Create a new Task object realm.writeBlocking { val task = create() task.name = "My First Task" task.isComplete = false Log.v("EXAMPLE", "Created task in Realm: ${task.name}") } // Query for all tasks and print them val tasks = realm.query().find() Log.v("EXAMPLE", "Tasks in Realm: ${tasks.size}") // Update a task realm.writeBlocking { val taskToUpdate = query().find().first() taskToUpdate.isComplete = true Log.v("EXAMPLE", "Updated task: ${taskToUpdate.name} - Complete: ${taskToUpdate.isComplete}") } // Delete a task realm.writeBlocking { val taskToDelete = query().find().first() delete(taskToDelete) Log.v("EXAMPLE", "Deleted task") } // Close the Realm instance realm.close() } } ``` -------------------------------- ### Quick Start for Unity with .NET SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Provides a quick start guide for integrating Realm with Unity, formerly titled 'Integrate Realm with Unity'. Includes a note about multiprocess-sync-related crashes. ```csharp using UnityEngine; using Realms; public class UnityQuickStart : MonoBehaviour { void Start() { // Example demonstrating Device Sync integration in Unity // var config = new RealmConfiguration("myRealm.realm") // { // SyncConfiguration = new SyncConfiguration(user, "partition") // }; // var realm = Realm.GetInstance(config); Debug.Log("Realm Unity Quick Start."); // ... rest of the application logic } } ``` -------------------------------- ### Complete Local Realm Example (Java) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/quick-starts/quick-start-local.txt A comprehensive Java example demonstrating the setup and usage of local Realm data, including object definition, creation, and modification. ```java package com.mongodb.realm.realm-java-quickstart; import android.os.Bundle; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import org.bson.types.ObjectId; import java.util.concurrent.ExecutionException; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Use Realm.getDefaultInstance() to get a Realm instance Realm realm = Realm.getDefaultInstance(); // Create a new Task object realm.writeBlocking(new WriteCallback() { @Override public void execute(WriteTransaction transaction) { Task task = transaction.create(Task.class); task.setName("My First Task"); task.setComplete(false); Log.v("EXAMPLE", "Created task in Realm: " + task.getName()); } }); // Query for all tasks and print them RealmList tasks = realm.query(Task.class).find(); Log.v("EXAMPLE", "Tasks in Realm: " + tasks.size()); // Update a task realm.writeBlocking(new WriteTransaction() { @Override public void execute(WriteTransaction transaction) { Task taskToUpdate = transaction.query(Task.class).find().first(); taskToUpdate.setComplete(true); Log.v("EXAMPLE", "Updated task: " + taskToUpdate.getName() + " - Complete: " + taskToUpdate.isComplete()); } }); // Delete a task realm.writeBlocking(new WriteTransaction() { @Override public void execute(WriteTransaction transaction) { Task taskToDelete = transaction.query(Task.class).find().first(); transaction.delete(taskToDelete); Log.v("EXAMPLE", "Deleted task"); } }); // Close the Realm instance realm.close(); } } // Define the Task object model class Task extends RealmObject { @PrimaryKey ObjectId _id; String name; boolean isComplete; String owner; // Default constructor public Task() { } // Getters and setters (required for Realm) public ObjectId get_id() { return _id; } public void set_id(ObjectId _id) { this._id = _id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isComplete() { return isComplete; } public void setComplete(boolean complete) { isComplete = complete; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } } // Define the TaskStatus object model class TaskStatus extends RealmObject { String name; // Default constructor public TaskStatus() { } // Getters and setters (required for Realm) public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### Clone and Navigate to Example App Source: https://github.com/mongodb/docs-realm/blob/master/source/web/sync.txt Clone the example app repository, checkout the correct branch, and navigate to the example project directory. ```sh git clone https://github.com/realm/realm-js.git cd realm-js git checkout nh/wasm/emscripten_target cd examples/example-react-task ``` -------------------------------- ### Quick Start with @realm/react conventions (React Native) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Rewrite of the React Native Quick Start guide to utilize the latest @realm/react conventions and Realm.js v12 features. ```javascript import React from 'react'; import { RealmProvider } from '@realm/react'; import TaskList from './TaskList'; function App() { return ( ); } ``` -------------------------------- ### Install Web SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Provides instructions for installing the Web SDK. ```bash npm install realm-web # or yarn add realm-web ``` -------------------------------- ### Checkout 'start' branch Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/quick-starts/livedata.txt Switch to the 'start' branch of the cloned repository to follow the tutorial steps. ```bash git checkout start ``` -------------------------------- ### Partition-Based Sync Example (Swift) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Provides an example of opening a Partition-Based Sync Realm in Swift. ```swift let app = App(id: YOUR_APP_ID) let partitionValue = "somePartition" let configuration = app.configuration(partitionValue: partitionValue) let realm = try! Realm(configuration: configuration) ``` -------------------------------- ### Installation: Define Install Directories Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/bundle_example/linux/CMakeLists.txt Defines the installation directories for bundle data and libraries within the installation prefix. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") ``` -------------------------------- ### Create a Flutter Project Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/flutter/install.txt Use these commands to create a new Flutter project. Refer to the official Flutter Installation Guide for more details. ```bash flutter create cd ``` -------------------------------- ### SwiftUI Example for Swift SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Includes a SwiftUI example demonstrating integration with the Swift SDK. ```swift import SwiftUI import RealmSwift struct ContentView: View { @ObservedResults(Task.self) var tasks var body: some View { NavigationView { List { ForEach(tasks) { task in Text(task.name) } .onDelete(perform: $tasks.remove) } .navigationTitle("Tasks") .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } // Define your Realm object model class Task: Object, Identifiable { @Persisted(primaryKey: true) var _id: ObjectId @Persisted var name: String = "" @Persisted var status: String = "" } ``` -------------------------------- ### start Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/mongodb/sync/SyncSession.txt Attempts to start the session and enable synchronization. ```APIDOC ## start ### Description Attempts to start the session and enable synchronization with the Realm Object Server. ### Method `start()` ``` -------------------------------- ### Kotlin SDK Example Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/kotlin/migrate-from-java-sdk-to-kotlin-sdk.txt Example code demonstrating equivalent functionality using the Kotlin SDK. ```kotlin import io.realm.kotlin.Realm import io.realm.kotlin.RealmConfiguration import org.junit.Test class MigrateFromJavaToKotlinSDKTest { @Test fun migrations() { // This is a placeholder for Kotlin SDK code. // Actual migration logic would be implemented here. println("Migrating from Kotlin SDK...") } } ``` -------------------------------- ### Install Application Executable Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/bundle_example/windows/CMakeLists.txt Installs the main application executable to the runtime destination directory. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Install Electron Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/node/integrations/electron-cra.txt Install Electron as a development dependency to add desktop application capabilities. ```shell npm install electron --save-dev ``` -------------------------------- ### Install Realm Web SDK Source: https://github.com/mongodb/docs-realm/blob/master/source/web/react-web-quickstart.txt Navigate into the created React app directory and install the realm-web package using npm. ```shell cd realm-web-react-quickstart npm install --save realm-web ``` -------------------------------- ### Java SDK Example Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/kotlin/migrate-from-java-sdk-to-kotlin-sdk.txt Example code demonstrating functionality using the Java SDK. ```java public class MigrateFromJavaToKotlinSDKTest { @Test public void migrations() { // This is a placeholder for Java SDK code. // Actual migration logic would be implemented here. System.out.println("Migrating from Java SDK..."); } } ``` -------------------------------- ### Installation: Install Bundled Libraries Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/bundle_example/linux/CMakeLists.txt Installs any bundled libraries required by plugins to the lib directory within the bundle. ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` -------------------------------- ### Fix Sync Query Error (Node.js) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md This example addresses a fix for an error in a Sync query code example within the Node.js SDK's Quick Start guide. ```javascript // Conceptual fix for a sync query error. // The actual code would be a corrected version of a query used for Realm Sync. ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/mongodb/docs-realm/blob/master/examples/node/v12/readme.md Run this command to install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Install Realm Dart SDK Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/README.md Installs the Realm Dart SDK. This is a required step before running generators or tests. ```sh dart run realm_dart install ``` -------------------------------- ### Add Filtering section with ObservedResults example Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Add a section about Filtering to the SwiftUI Guide, including a new ObservedResults type-safe query example. ```swift import SwiftUI import RealmSwift struct ContentView: View { @ObservedResults(Task.self, filter: (".name == \"Important\"")) var tasks: Results var body: some View { List(tasks) { task in Text(task.name) } } } // Assuming Task is a RealmObject with a 'name' property. ``` -------------------------------- ### Initialize Realm App with Configuration (C++) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Update App init examples to use `realm::App(configuration)`. ```cpp configuration: app_id: "your_app_id" # ... other configuration options ``` -------------------------------- ### RQL Schema Examples (.NET SDK) Source: https://github.com/mongodb/docs-realm/blob/master/source/realm-query-language.txt Example of RQL schema definition using the .NET SDK. ```csharp var quota = null ``` -------------------------------- ### Run the React App Source: https://github.com/mongodb/docs-realm/blob/master/source/web/react-web-quickstart.txt Start the local web server for your React application using the yarn start command. ```shell yarn start ``` -------------------------------- ### Extract SwiftUI View Examples with Bluehawk Source: https://github.com/mongodb/docs-realm/blob/master/examples/ios/README.md Use the Bluehawk CLI to extract code examples from SwiftUI view files. ```bash bluehawk snip -o source/examples/generated/swiftui/ examples/ios/SwiftUICatalog ``` -------------------------------- ### Basic CMake Project Setup Source: https://github.com/mongodb/docs-realm/blob/master/examples/dart/bundle_example/windows/CMakeLists.txt Initializes CMake version and project name. Sets the executable name and opts into modern CMake behaviors. ```cmake cmake_minimum_required(VERSION 3.14) project(bundle_example LANGUAGES CXX) set(BINARY_NAME "bundle_example") cmake_policy(SET CMP0063 NEW) ``` -------------------------------- ### Open Xcode Project Source: https://github.com/mongodb/docs-realm/blob/master/examples/ios/README.md Open the RealmExamples.xcodeproj file with Xcode to run unit tests for Swift and Objective-C iOS examples. ```bash open RealmExamples.xcodeproj ``` -------------------------------- ### Migrate from Java SDK to Kotlin SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md This guide provides tested code examples for migrating from the Java SDK to the Kotlin SDK. ```kotlin // Example migration snippet (conceptual) // Replace Java SDK specific calls with Kotlin SDK equivalents. // Refer to the official migration guide for detailed examples. ``` -------------------------------- ### Initial Subscriptions for Flexible Sync in Node.js SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Demonstrates setting up initial subscriptions for Flexible Sync in the Node.js SDK. ```javascript const realm = await Realm.open({ sync: { user, flexible: true, initialSubscriptions: { rerunOnOpen: true, update: (subs) => { subs.add(realm.objects('Task'), { name: 'all-tasks' }); } } } }); ``` -------------------------------- ### METHOD_NOT_ALLOWED Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/mongodb/ErrorCode.txt Indicates that the HTTP method used for a request is not allowed for the target resource. For example, using GET on an endpoint that only supports POST. ```APIDOC ## METHOD_NOT_ALLOWED ### Description This error code is returned when an HTTP request uses a method (e.g., GET, POST) that is not permitted for the specified resource. Check the API documentation for allowed methods. ### Error Code `METHOD_NOT_ALLOWED` ``` -------------------------------- ### Create Electron BrowserWindow and Load HTML Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/node/integrations/electron.txt Sets up the main process script (main.js) to create a BrowserWindow and load the index.html file. It also includes a process.stdin.resume() call to prevent premature Sync Connection termination. ```javascript const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false } }) // to prevent the Sync Connection from ending prematurely, start reading from stdin so we don't exit process.stdin.resume(); win.loadFile('index.html') } app.whenReady().then(createWindow) ``` -------------------------------- ### Define Teacher and Student Schemas Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/crud/filter-data.txt Defines the schema for Teacher and Student Realm objects. This setup is required for the subsequent query examples. ```java public class Teacher extends RealmObject { @PrimaryKey private ObjectId id = new ObjectId(); private String name; private int age; private RealmList students; private Student primaryStudent; // Constructors, getters, and setters } public class Student extends RealmObject { @PrimaryKey private ObjectId id = new ObjectId(); private String name; private int age; // Constructors, getters, and setters } ``` ```java public class Teacher extends RealmObject { @PrimaryKey private ObjectId id = new ObjectId(); private String name; private int age; private RealmList students; private Student primaryStudent; // Constructors, getters, and setters } public class Student extends RealmObject { @PrimaryKey private ObjectId id = new ObjectId(); private String name; private int age; // Constructors, getters, and setters } ``` -------------------------------- ### Complete MainActivity Example in Java Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/quick-starts/quick-start-sync.txt A comprehensive example demonstrating the integration of Realm SDK for Android in Java, covering object creation, retrieval, updates, deletion, and change listeners. ```java package com.yourcompany.realmquickstart; import android.os.Bundle; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import org.bson.types.ObjectId; import java.util.concurrent.ExecutionException; import io.realm.Realm; import io.realm.Realm.Transaction.Handler; import io.realm.Realm.Transaction.OnError; import io.realm.Realm.Transaction.OnSuccess; import io.realm.RealmConfiguration; import io.realm.RealmObject; import io.realm.RealmResults; import io.realm.mongodb.App; import io.realm.mongodb.AppConfiguration; import io.realm.mongodb.Credentials; import io.realm.mongodb.User; import io.realm.mongodb.exceptions.RealmFileException; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private App app; private User user; private Realm realm; private App.Callback loginCallback = new App.Callback() { @Override public void onSuccess(App.Result result) { user = result.get(); Log.v(TAG, "Successfully authenticated anonymously."); // Get a Realm instance RealmConfiguration config = new RealmConfiguration.Builder() .allowWritesOnUiThread(true) .build(); realm = Realm.getInstance(config); // Create a new Task Task task = new Task(); task.setId(new ObjectId().toString()); task.setSummary("This is a task"); task.setComplete(false); // Add the Task to the Realm realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealm(task); } }, new OnSuccess() { @Override public void onSuccess() { Log.v(TAG, "Successfully created task."); // Query for tasks RealmResults tasks = realm.where(Task.class).findAll(); Log.v(TAG, "Query results: " + tasks.size()); // Update a task realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Task taskToUpdate = realm.where(Task.class).findFirst(); if (taskToUpdate != null) { taskToUpdate.setSummary("Updated task summary"); taskToUpdate.setComplete(true); Log.v(TAG, "Successfully updated task."); } } }, new OnSuccess() { @Override public void onSuccess() { Log.v(TAG, "Update successful."); // Delete a task realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Task taskToDelete = realm.where(Task.class).findFirst(); if (taskToDelete != null) { taskToDelete.deleteFromRealm(); Log.v(TAG, "Successfully deleted task."); } } }, new OnSuccess() { @Override public void onSuccess() { Log.v(TAG, "Delete successful."); // Close the realm realm.close(); } }, new OnError() { @Override public void onError(Object error) { Log.e(TAG, "Delete failed: " + error.toString()); realm.close(); } }); } }, new OnError() { @Override public void onError(Object error) { Log.e(TAG, "Update failed: " + error.toString()); realm.close(); } }); } }, new OnError() { @Override public void onError(Object error) { Log.e(TAG, "Create task failed: " + error.toString()); realm.close(); } }); } @Override public void onError(App.Result result) { Log.e(TAG, "Authentication failed: " + result.getError().toString()); if (result.getError() instanceof RealmFileException) { RealmFileException realmFileException = (RealmFileException) result.getError(); // handle realm file errors } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String appId = getString(R.string.APP_ID); app = new App(new AppConfiguration.Builder(appId) .defaultAppLanguage("en") .build()); Credentials credentials = Credentials.anonymous(); app.loginAsync(credentials, loginCallback); } @Override protected void onDestroy() { super.onDestroy(); if (realm != null && !realm.isClosed()) { realm.close(); } } } ``` -------------------------------- ### Create a Node.js Project Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/node/install.txt Create a new directory for your project and initialize it with npm. Replace 'MyApp' with your project's name. ```bash mkdir MyApp && cd MyApp && npm init ``` -------------------------------- ### Define Teacher and Student Schemas Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/crud/filter-data.txt Defines the schema for Teacher and Student Realm objects. This setup is required for the subsequent query examples. ```kotlin open class Teacher(@PrimaryKey var id: ObjectId = ObjectId(), var name: String = "", var age: Int = 0, var students: RealmList = RealmList(), var primaryStudent: Student? = null) : RealmObject() open class Student(@PrimaryKey var id: ObjectId = ObjectId(), var name: String = "", var age: Int = 0) : RealmObject() ``` ```kotlin open class Teacher(@PrimaryKey var id: ObjectId = ObjectId(), var name: String = "", var age: Int = 0, var students: RealmList = RealmList(), var primaryStudent: Student? = null) : RealmObject() open class Student(@PrimaryKey var id: ObjectId = ObjectId(), var name: String = "", var age: Int = 0) : RealmObject() ``` -------------------------------- ### Create a React Native Project Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/react-native/install.txt Initialize a new React Native project using the react-native CLI. ```bash react-native init MyApp ``` -------------------------------- ### Get and Refresh User Access Token (Swift) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Provides code examples for obtaining and refreshing a user access token in a Swift application. ```swift let user = app.currentUser user.refreshCustomData { (result) in switch result { case .success(let customData): print("Successfully refreshed custom data: \(customData)") case .failure(let error): print("Failed to refresh custom data: \(error.localizedDescription)") } } ``` -------------------------------- ### Create a Standalone Dart Project Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/flutter/install.txt Use these commands to create a new standalone Dart project. Refer to the official Dart Installation Guide for more details. ```bash dart create cd ``` -------------------------------- ### Access MongoDB Collections Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/mongodb/App.txt Access a specific MongoDB collection within a Realm App. This example shows how to get a collection and perform a count operation. ```java MongoClient client = user.getMongoClient(SERVICE_NAME) MongoDatabase database = client.getDatabase(DATABASE_NAME) MongoCollection collection = database.getCollection(COLLECTION_NAME); Long count = collection.count().get() ``` -------------------------------- ### Bootstrap Realm with Initial Subscription in .NET SDK Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Code example for bootstrapping a Realm with an initial subscription using the .NET SDK. ```csharp var config = new RealmConfiguration("myRealm.realm") { ObjectClasses = new[] { typeof(MyObject) }, SyncConfiguration = new SyncConfiguration("userToken", new Uri("...app.realm.mongodb.com")) { Flexibility = { InitialSubscriptions = (realm) => { realm.Subscriptions.Add(new Subscription("mySubscription", realm.All())); } } } }; var realm = Realm.GetInstance(config); ``` -------------------------------- ### Compaction Logic Example Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/swift/realm-files/compacting.txt This Swift code provides an example of the logic for the `shouldCompactOnLaunch` callback. It checks if the Realm file size exceeds a maximum limit and if more than 50% of the file is unused space. ```swift // Set a maxFileSize equal to 20MB in bytes let maxFileSize = 20 * 1024 * 1024 // Check for the realm file size to be greater than the max file size, // and the amount of bytes currently used to be less than 50% of the // total realm file size return (realmFileSizeInBytes > maxFileSize) && (Double(usedBytes) / Double(realmFileSizeInBytes)) < 0.5 ``` -------------------------------- ### Set a Custom Logger Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/flutter/logging.txt To get started with custom logging, set a log level. The Flutter SDK logger conforms to the Dart Logger class. ```dart import 'package:realm/realm.dart'; void main() { // Set the log level to 'info' to start using the logger. Realm.logLevel = LogLevel.info; } ``` -------------------------------- ### Reset Client Realm (Node.js) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Example of resetting a client Realm in the Node.js SDK. This is typically done to recover from sync errors or to start with a fresh state. ```javascript await realm.syncSession.clientResetRealmAsync(); ``` -------------------------------- ### Populate MongoDB Collection with Example Data in Java Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/app-services/mongodb-remote-access.txt Inserts sample plant data into a MongoDB collection. This setup is used for subsequent read and write operations. ```java package io.realm.app.examples.mongodb; import io.realm.mongodb.App; import io.realm.mongodb.Credentials; import io.realm.mongodb.User; import io.realm.mongodb.mongodb.MongoClient; import io.realm.mongodb.mongodb.MongoCollection; import io.realm.mongodb.mongodb.MongoDatabase; import org.bson.Document; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class MongoDBDataAccessTest { @Test public void exampleData() { // ... other setup code ... App app = new App(new App.Configuration.Builder("your-app-id") // Replace with your App ID .build()); User user = app.login(Credentials.anonymous()); MongoClient mongoClient = user.getMongoClient("mongodb-atlas"); MongoDatabase database = mongoClient.getDatabase("sample_plants"); MongoCollection collection = database.getCollection("plants"); // Clear existing data for a clean slate collection.deleteMany(new Document()).get(); // Insert sample documents List plants = new ArrayList<>(); plants.add(new Plant("Venus Flytrap", "Carnivorous", 6.0, 4.99, true, "Greenhouse")); plants.add(new Plant("Peace Lily", "Flowering", 4.0, 2.99, false, "Indoor")); plants.add(new Plant("Snake Plant", "Foliage", 2.0, 12.99, false, "Indoor")); plants.add(new Plant("Sunflower", "Flowering", 8.0, 1.99, true, "Outdoor")); plants.add(new Plant("Orchid", "Flowering", 3.0, 25.99, false, "Indoor")); for (Plant plant : plants) { collection.insertOne(plant).get(); } System.out.println("Successfully inserted example data."); } } ``` -------------------------------- ### Populate MongoDB Collection with Example Data in Kotlin Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/app-services/mongodb-remote-access.txt Inserts sample plant data into a MongoDB collection. This setup is used for subsequent read and write operations. ```kotlin import io.realm.mongodb.App import io.realm.mongodb.Credentials import io.realm.mongodb.User import io.realm.mongodb.mongodb.MongoClient import io.realm.mongodb.mongodb.MongoCollection import io.realm.mongodb.mongodb.MongoDatabase import org.bson.Document import kotlinx.coroutines.runBlocking import org.junit.Test class MongoDBDataAccessTest { @Test fun exampleData() = runBlocking { // ... other setup code ... val app: App = App.create("your-app-id") // Replace with your App ID val user: User = app.login(Credentials.anonymous()) val mongoClient: MongoClient = user.getMongoClient("mongodb-atlas") val database: MongoDatabase = mongoClient.getDatabase("sample_plants") val collection: MongoCollection = database.getCollection("plants") // Clear existing data for a clean slate collection.deleteMany(Document()).get() // Insert sample documents val plants = listOf( Plant("Venus Flytrap", "Carnivorous", 6.0, 4.99, true, "Greenhouse"), Plant("Peace Lily", "Flowering", 4.0, 2.99, false, "Indoor"), Plant("Snake Plant", "Foliage", 2.0, 12.99, false, "Indoor"), Plant("Sunflower", "Flowering", 8.0, 1.99, true, "Outdoor"), Plant("Orchid", "Flowering", 3.0, 25.99, false, "Indoor") ) for (plant in plants) { collection.insertOne(plant).get() } println("Successfully inserted example data.") } } ``` -------------------------------- ### Configure and Open a Realm (C++ SDK) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Demonstrates how to configure and open a Realm database using the C++ SDK. This is useful for setting up local Realm instances for your application. ```cpp #include int main() { // Define Realm configuration realm::Realm::Config config; config.path = "myrealm.realm"; // Open the Realm auto realm = realm::Realm::get_shared(config); // Use the Realm instance... return 0; } ``` -------------------------------- ### String Operators for Filtering Projects Source: https://github.com/mongodb/docs-realm/blob/master/source/realm-query-language.txt Utilizes string operators to find projects based on their names. This example finds projects starting with 'e' and projects containing 'ie'. ```javascript realm.objects('Project').filtered("name BEGINSWITH $0", 'e') realm.objects('Project').filtered("name CONTAINS $0", 'ie') ``` -------------------------------- ### Connect to App Services (Flutter) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Access an App instance on a background isolate when connecting to Atlas App Services in Flutter. This example demonstrates how to get an App by its ID. ```dart Future openRealm() async { final app = Realm.App(AppConfiguration("your-app-id")); final user = await app.logIn(Credentials.anonymous()); final config = Configuration.flexibleSync(user, "your-realm-name"); return Realm.open(config); } ``` -------------------------------- ### String Operators in JavaScript Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/node/crud/query-data.txt Compare string properties using operators like 'beginsWith', 'contains', and 'LIKE'. This example finds projects starting with 'e' and projects containing 'ie'. ```javascript const projectsStartingWithE = realm.objects('Project').filtered('name BEGINSWITH "e"'); const projectsWithNameContainingIE = realm.objects('Project').filtered('name LIKE "*ie*"'); ``` -------------------------------- ### Annotate Code Snippets with Bluehawk Source: https://github.com/mongodb/docs-realm/blob/master/examples/java/local/README.md This Swift code demonstrates how to use Bluehawk annotations to mark the start and end of code examples for extraction. It also shows how to exclude specific lines from the extracted snippet. ```swift // :snippet-start: example ... some code for the code example ... // :remove-start: some code that should not be in the code example // :remove-end: ... some more code for the code example ... // :snippet-end: ``` -------------------------------- ### Realm.init(Context context) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/Realm.txt Initializes the Realm library and creates a default configuration that is ready to use. This is a simpler initialization method. ```APIDOC ## Realm.init(Context context) ### Description Initializes the Realm library and creates a default configuration that is ready to use. This is a simpler initialization method. ### Method ```java public static synchronized void init(Context context) ``` ### Parameters #### Path Parameters - **context** (Context) - Required - The application context. ``` -------------------------------- ### Subscription Setup for Synced Realm Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/flutter/sync/write-to-synced-realm.txt Configures the Realm SDK to synchronize objects matching a specific query. This example sets up a subscription for 'Car' objects where the ownerId matches the current user's ID. ```dart final config = Configuration.flexibleSync(user, 'myApp.12345', initialSubscriptions: (realm) async { realm.subscriptions.update((mutableSubscriptions) { mutableSubscriptions.add(Query(Car.schema.name), name: 'my_cars'); }); }); final realm = await Realm.open(config); ``` -------------------------------- ### String Operators for Flexible Matching (Java) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/crud/filter-data.txt Utilize string operators like beginsWith, contains, endsWith, like, and equalTo for flexible text-based queries. This example finds projects starting with 'e' and containing 'ie'. ```java RealmResults projectsStartingWithE = realm.query(Project.class, "name beginsWith \"e\"").findAll(); RealmResults projectsContainingIE = realm.query(Project.class, "name contains \"ie\"").findAll(); ``` -------------------------------- ### Basic RealmProvider Setup Source: https://github.com/mongodb/docs-realm/blob/master/source/examples/generated/react-native/v12/RealmWrapper.snippet.qs-realm-provider.tsx.rst Use RealmProvider to wrap your application and provide Realm access. Ensure you import your data models and pass them in the schema prop. ```typescript import React from 'react'; import {RealmProvider} from '@realm/react'; // Import your models import {Profile} from '../../../models'; export const AppWrapper = () => { return ( ); }; ``` -------------------------------- ### Create and Manage API Keys (Web SDK) Source: https://github.com/mongodb/docs-realm/blob/master/docs-release-notes.md Code examples for creating and managing API keys using the Web SDK. ```javascript const app = new Realm.App({ id: "your-app-id" }); async function createApiKey() { const apiKey = await app.currentUser.createApiKey("My API Key Name"); console.log("API Key created:", apiKey.key); return apiKey; } async function listApiKeys() { const apiKeys = await app.currentUser.listApiKeys(); console.log("API Keys:", apiKeys); return apiKeys; } async function deleteApiKey(id) { await app.currentUser.deleteApiKey(id); console.log("API Key deleted."); } ``` -------------------------------- ### String Operators for Flexible Matching (Kotlin) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/crud/filter-data.txt Utilize string operators like beginsWith, contains, endsWith, like, and equalTo for flexible text-based queries. This example finds projects starting with 'e' and containing 'ie'. ```kotlin val projectsStartingWithE = realm.query("name beginsWith \"e\"").find() val projectsContainingIE = realm.query("name contains \"ie\"").find() ``` -------------------------------- ### Install Web SDK with npm Source: https://github.com/mongodb/docs-realm/blob/master/source/web/install.txt Use this command to install the Realm Web SDK using npm. This is the standard method for Node.js-based projects. ```shell npm install realm-web ``` -------------------------------- ### Manual Realm SDK Dependency Setup for Android (Kotlin) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/test-and-debug/troubleshooting.txt Manually configure Realm SDK dependencies in your Android application's build.gradle file when customizing beyond the standard Gradle plugin. This example uses Kotlin. ```gradle buildscript { ext.kotlin_version = '1.5.21' ext.realm_version = '{+java-sdk-version+}' repositories { jcenter() mavenCentral() } dependencies { classpath "io.realm:realm-transformer:$realm_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' import io.realm.transformer.RealmTransformer android.registerTransform(new RealmTransformer(project)) dependencies { api "io.realm:realm-annotations:$realm_version" api "io.realm:realm-android-library:$realm_version" api "io.realm:realm-android-kotlin-extensions:$realm_version" kapt "io.realm:realm-annotations-processor:$realm_version" } ``` -------------------------------- ### Bootstrap Realm with Initial Subscriptions and Rerun on Open Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/swift/sync/flexible-sync.txt Illustrates bootstrapping a Realm with initial subscriptions that dynamically recalculate each time the app starts, using the `rerunOnOpen` parameter. ```swift let sevenDaysAgo = Date().addingTimeInterval(-7 * 24 * 60 * 60) let sevenDaysFromNow = Date().addingTimeInterval(7 * 24 * 60 * 60) let config = flexibleSyncConfiguration(user: user, initialSubscriptions: .init(subscriptions: [ Subscription(query: "due_date >= \(sevenDaysAgo)" ), Subscription(query: "due_date <= \(sevenDaysFromNow)") ], rerunOnOpen: true)) let realm = try! await Realm(configuration: config) ``` -------------------------------- ### Jest Test Setup and Teardown for Realm React Native SDK Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/react-native/test-and-debug/testing.txt This example demonstrates how to use Jest's `beforeEach()` and `afterEach()` hooks to set up and tear down tests involving the Realm React Native SDK. It includes closing realms and deleting realm files for proper test cleanup. ```javascript import Realm from "realm"; describe('Realm Tests', () => { let realm; beforeEach(async () => { // Open a realm for each test realm = await Realm.open({ schema: [Car.schema], // Use an in-memory realm for faster tests inMemory: true, }); }); afterEach(() => { // Close the realm and delete the file if (realm) { realm.close(); Realm.deleteFile(realm.path); } }); it('should create and query a car', () => { // Test logic using the realm instance realm.write(() => { realm.create(Car.schema.name, { make: 'Toyota', model: 'Camry', year: 2022, }); }); const cars = realm.objects(Car.schema.name); expect(cars.length).toBe(1); expect(cars[0].make).toBe('Toyota'); }); }); ``` -------------------------------- ### Create, Write, and Read Sets in C# Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/dotnet/model-data/data-types/sets.txt This example shows how to instantiate a Realm, create an object with Sets, add elements to the Sets, and query them. It covers adding primitive types, nullable types, and Realm objects to Sets. ```csharp var realm = await Realm.GetInstanceAsync(new PartitionSyncConfiguration("my-partition", anonymou sIdentity)); realm.Write(() => { var user = realm.Add(new User()); // Add primitive types user.FavoriteNumbers.Add(1); user.FavoriteNumbers.Add(2); user.FavoriteStrings.Add("apple"); user.FavoriteStrings.Add("banana"); // Add nullable types user.FavoriteNullableNumbers.Add(3); user.FavoriteNullableNumbers.Add(null); user.FavoriteNullableStrings.Add("cherry"); user.FavoriteNullableStrings.Add(null); // Add Realm objects var car1 = realm.Add(new Car { Make = "Toyota", Model = "Camry" }); var car2 = realm.Add(new Car { Make = "Honda", Model = "Civic" }); user.FavoriteCars.Add(car1); user.FavoriteCars.Add(car2); }); // Query Sets Console.WriteLine($"User has {user.FavoriteNumbers.Count} favorite numbers."); Console.WriteLine($"User has {user.FavoriteCars.Count} favorite cars."); foreach (var number in user.FavoriteNumbers) { Console.WriteLine($"Favorite number: {number}"); } foreach (var car in user.FavoriteCars) { Console.WriteLine($"Favorite car: {car.Make} {car.Model}"); } ``` -------------------------------- ### Initialize CocoaPods for Project Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/swift/install.txt Create a Podfile for your project if one does not already exist by running 'pod init' in the project's root directory. ```sh pod init ``` -------------------------------- ### Install CMake using Homebrew Source: https://github.com/mongodb/docs-realm/blob/master/examples/cpp/README.md Install CMake on macOS using the Homebrew package manager if it is not already installed. ```shell brew install cmake ``` -------------------------------- ### Minimal SyncConfiguration Setup Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/mongodb/sync/SyncConfiguration.txt Creates a default SyncConfiguration for a given user and partition value, then opens a synchronized Realm instance. Requires an authenticated User object and a partition value. ```java App app = new App("app-id"); User user = app.login(Credentials.anonymous()); SyncConfiguration config = SyncConfiguration.defaultConfiguration(user, "partition-value"); Realm realm = Realm.getInstance(config); ``` -------------------------------- ### Example CoffeeDrink Document Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/swift/app-services/mongodb-remote-access.txt An example of a CoffeeDrink document structure used in aggregation examples, featuring 'store' as a string field. ```swift let storeDocument = [ "name": "Bean of the Day", "store": "Store 42", "containsDairy": false, "beanRegion": "Timbio, Colombia" ] ``` -------------------------------- ### Configure MainApplication.java Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/react-native/install.txt Import RealmReactPackage and add it to the packages list in MainApplication.java for Android. ```java import io.realm.react.RealmReactPackage; // Add this import. public class MainApplication extends Application implements ReactApplication { @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RealmReactPackage() // Add this line. ); } // ... ``` -------------------------------- ### Realm.init(Context context, String userAgent) Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/Realm.txt Initializes the Realm library and creates a default configuration that is ready to use. This version includes a user agent string. ```APIDOC ## Realm.init(Context context, String userAgent) ### Description Initializes the Realm library and creates a default configuration that is ready to use. This version includes a user agent string. ### Method ```java public static synchronized void init(Context context, String userAgent) ``` ### Parameters #### Path Parameters - **context** (Context) - Required - The application context. - **userAgent** (String) - Required - The user agent string. ### Parameters #### Path Parameters - **context** (Context) - Required - The application context. - **userAgent** (String) - Required - The user agent string. ``` -------------------------------- ### Install Electron and Realm Dependencies Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/node/integrations/electron.txt Installs the necessary Electron development dependency and the Realm SDK. Realm is installed specifically at version 12. ```shell npm install electron --save-dev npm install realm@12 --save ``` -------------------------------- ### build Source: https://github.com/mongodb/docs-realm/blob/master/source/sdk/java/api/io/realm/mongodb/AppConfiguration/Builder.txt Creates the AppConfiguration. ```APIDOC ## build() ### Description Creates the AppConfiguration. ```