Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

Create Specific Object Types

On this page

  • Create Specific SDK Object Types
  • Create a Realm Object
  • Create an Embedded Object
  • Create an Asymmetric Object
  • Create a Geospatial Data Object

This page describes how to create specific types of objects using Atlas Device SDK. To learn more about object models and how to define them, refer to Define an SDK Object Model.

You can create objects whose object type is managed by the database instance. For more information, refer to Configure & Open a Database File or Configure & Open a Synced Database.

For more information about write transactions and the methods you can use to create an object, refer to Create Objects.

For information about creating specific property types, including special types, collections, and relationship properties, refer to Create Specific Property Types.

Before you can create a new object and persist it to the database, you must Define an SDK Object Model. Then, include that object type in your database schema when you open the database.

Important

Object Types Must Be in Your Schema

You can only write objects whose object type is included in the database schema. If you try to reference or write an object of an object type that isn't in your schema, the SDK returns a schema validation error.

The SDK refers to the base object type as a Realm object. This identifies it as an object type that can be managed by the device persistence layer, Realm database.

To create an object, you must instantiate it using the realm namespace. Move the object into the database using the Realm.add() function inside of a write transaction.

When you move an object into a database, this consumes the object as an rvalue. You must use the managed object for any data access or observation. In this example, copying the dog object into the database consumes it as an rvalue. You can return the managed object to continue to work with it.

The following code shows two methods for creating a new Realm object. In the first example, we create the object first, and then add it to the realm within a WriteAsync() method. In the second example, we create the document within the WriteAsync block, which returns a realm object we can further work with.

Once you've opened a database, you can create objects within it using a Realm.write() transaction block.

realm.write((){
// ...write data to realm
});

You can also return values from the write transaction callback function.

Use realm.createObject() in a transaction to create a persistent instance of a database object. You can then modify the returned object with other field values using accessors and mutators.

The following example demonstrates how to create an object with createObject():

To add an object to a database, instantiate it as you would any other object and then pass it to Realm.create() inside of a write transaction. If the database schema includes the object type and the object conforms to the schema, then the SDK stores the object, which is now managed by the database instance.

To create a new RealmObject instance, instantiate a new object of a realm object type.

In the following example, we instantiate a Frog object in a realm.write() block, then pass the instantiated object to copyToRealm() to return a managed instance:

Use realm.createObject() in a transaction to create a persistent instance of a database object. You can then modify the returned object with other field values using accessors and mutators.

The following example demonstrates how to create an object with createObject():

To add an object to a database, instantiate it as you would any other object and then pass it to -[RLMRealm addObject:] inside of a write transaction.

To add an object to a database, instantiate it as you would any other object and then pass it to Realm.add(_:update:) inside of a write transaction.

To add an object to a database, instantiate it as you would any other object and then pass it to Realm.create() inside of a write transaction. If the database schema includes the object type and the object conforms to the schema, then the SDK stores the object, which is now managed by the database instance.

// Create an object using the `realm` namespace.
auto dog = realm::Dog{.name = "Rex", .age = 1};
std::cout << "dog: " << dog.name << "\n";
// Open the database with compile-time schema checking.
auto config = realm::db_config();
auto realm = realm::db(std::move(config));
// Persist your data in a write transaction
// Optionally return the managed object to work with it immediately
auto managedDog = realm.write([&] { return realm.add(std::move(dog)); });
var testItem = new Item
{
Name = "Do this thing",
Status = ItemStatus.Open.ToString(),
Assignee = "Aimee"
};
await realm.WriteAsync(() =>
{
realm.Add(testItem);
});
// Or
var testItem2 =
await realm.WriteAsync(() =>
{
return realm.Add<Item>(new Item
{
Name = "Do this thing, too",
Status = ItemStatus.InProgress.ToString(),
Assignee = "Satya"
});
}
);
final yoda = realm.write<Person>(() {
return realm.add(Person(ObjectId(), 'Yoda'));
});
realm.executeTransaction(r -> {
// Instantiate the class using the factory function.
Turtle turtle = r.createObject(Turtle.class, new ObjectId());
// Configure the instance.
turtle.setName("Max");
// Create a TurtleEnthusiast with a primary key.
ObjectId primaryKeyValue = new ObjectId();
TurtleEnthusiast turtleEnthusiast = r.createObject(TurtleEnthusiast.class, primaryKeyValue);
});
// Declare the variable that will hold the dog instance.
let dog;
// Open a transaction.
realm.write(() => {
// Assign a newly-created instance to the variable.
dog = realm.create("Dog", { name: "Max", age: 5 });
});
// use newly created dog object
// Open a write transaction
realm.write {
// Instantiate a new unmanaged Frog object
val unmanagedFrog = Frog().apply {
name = "Kermit"
age = 42
owner = "Jim Henson"
}
assertFalse(unmanagedFrog.isManaged())
// Copy the object to realm to return a managed instance
val managedFrog = copyToRealm(unmanagedFrog)
assertTrue(managedFrog.isManaged())
// Work with the managed object ...
}
realm.executeTransaction { r: Realm ->
// Instantiate the class using the factory function.
val turtle = r.createObject(Turtle::class.java, ObjectId())
// Configure the instance.
turtle.name = "Max"
// Create a TurtleEnthusiast with a primary key.
val primaryKeyValue = ObjectId()
val turtleEnthusiast = r.createObject(
TurtleEnthusiast::class.java,
primaryKeyValue
)
}
// Get the default realm.
// You only need to do this once per thread.
RLMRealm *realm = [RLMRealm defaultRealm];
// Instantiate the class.
Dog *dog = [[Dog alloc] init];
dog.name = @"Max";
dog.age = 5;
// Open a thread-safe transaction.
[realm transactionWithBlock:^() {
// Add the instance to the realm.
[realm addObject:dog];
}];
// Instantiate the class and set its values.
let dog = Dog()
dog.name = "Rex"
dog.age = 10
// Get the default realm. You only need to do this once per thread.
let realm = try! Realm()
// Open a thread-safe transaction.
try! realm.write {
// Add the instance to the realm.
realm.add(dog)
}
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

For more information about modeling an object, refer to Define an SDK Object Model.

namespace realm {
struct Dog {
std::string name;
int64_t age;
};
REALM_SCHEMA(Dog, name, age)
} // namespace realm
public partial class Item : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; } = ObjectId.GenerateNewId();
[MapTo("assignee")]
public string Assignee { get; set; }
[MapTo("name")]
public string? Name { get; set; }
[MapTo("status")]
public string? Status { get; set; }
}
@RealmModel()
class _Person {
@PrimaryKey()
late ObjectId id;
late String name;
late List<String> hobbies;
}
@RealmModel()
class _Team {
@PrimaryKey()
late ObjectId id;
late String name;
late List<_Person> crew;
late RealmValue eventLog;
}
// The documentation does not have this code example in Java.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Kotlin.
// Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Kotlin for the Java SDK.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

To create a new embedded object instance, assign an instance of an embedded object type to a parent object's property. This can be in a one-to-one, one-to-many, or inverse relationship depending on how you defined the embedded object within the parent object type.

Note

Embedded Objects Must Be Created Within a Parent Object

An embedded object requires a parent object and cannot exist as an independent SDK object.

Embedded objects have strict ownership with their parent object. After you create the embedded object, you cannot reassign it to a different parent object or share it between multiple parent objects.

To create an embedded object, assign the raw pointer of the embedded object to a parent object's property. Move the parent object into the database using the Realm.add() function inside of a write transaction.

In this example, we assign the raw pointer of the embedded object - ContactDetails * - to the embedded object property of the parent object - Business.contactDetails.

Then, we add the business object to the database. This copies the business and contactDetails objects to the database.

Because ContactDetails is an embedded object, it does not have its own lifecycle independent of the main Business object. If you delete the Business object, this also deletes the ContactDetails object.

To create an embedded object, assign an instance of the embedded object to a parent object's property:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

In the following example, we instantiate a new Contact object with an embedded Address, which contains a Contact object and an embedded Country object:

realm.write {
// Instantiate a parent object with one embedded address
val contact = Contact().apply {
name = "Kermit"
address = EmbeddedAddress().apply {
propertyOwner = Contact().apply { name = "Mr. Frog" }
street = "123 Pond St"
country = EmbeddedCountry().apply { name = "United States" }
}
}
// Copy all objects to the realm to return managed instances
copyToRealm(contact)
}

We also instantiate a new Business object with a list of embedded Address objects, which also contain Contact objects and embedded Country objects:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

To create an embedded object, assign an instance of the embedded object to a parent object's property:

auto config = realm::db_config();
auto realm = realm::db(std::move(config));
auto contactDetails = realm::ContactDetails{
.emailAddress = "email@example.com", .phoneNumber = "123-456-7890"};
auto business = realm::Business();
business._id = realm::object_id::generate();
business.name = "MongoDB";
business.contactDetails = &contactDetails;
realm.write([&] { realm.add(std::move(business)); });
var address = new Address() // Create an Address
{
Street = "123 Fake St.",
City = "Springfield",
Country = "USA",
PostalCode = "90710"
};
var contact = new Contact() // Create a Contact
{
Name = "Nick Riviera",
Address = address // Embed the Address Object
};
realm.Write(() =>
{
realm.Add(contact);
});
// The documentation does not currently have this code example in Dart.
// Please refer to the other languages or related pages for example code.
User user = app.currentUser();
String partitionValue = "My Project";
SyncConfiguration config = new SyncConfiguration.Builder(user, partitionValue)
.build();
Realm realm = Realm.getInstance(config);
Address address = new Address("123 Fake St.", "Springfield", "USA", "90710");
Contact contact = new Contact("Nick Riviera", address);
realm.executeTransaction(transactionRealm -> {
transactionRealm.insert(contact);
});
realm.close();
// create an embedded address object
const sydneyOrthodontics = {
street: "42 Wallaby Way",
city: "Sydney",
country: "Australia",
postalCode: "2774",
};
realm.write(() => {
// create a contact object
realm.create("Contact", {
_id: new BSON.ObjectId(),
name: "Philip Sherman",
address: sydneyOrthodontics, // embed the address in the contact object
});
});
realm.write {
// Instantiate a parent object with multiple embedded addresses
val localOffice = EmbeddedAddress().apply {
propertyOwner = Contact().apply { name = "Michigan J. Frog" }
street = "456 Lily Pad Ln"
country = EmbeddedCountry().apply { name = "United States" }
}
val remoteOffice = EmbeddedAddress().apply {
propertyOwner = Contact().apply { name = "Mr. Toad" }
street = "789 Leaping Frog Ave"
country = EmbeddedCountry().apply { name = "Ireland" }
}
val business = Business().apply {
name = "Big Frog Corp."
addresses = realmListOf(localOffice, remoteOffice)
}
// Copy all objects to the realm to return managed instances
copyToRealm(business)
}
val user: User? = app.currentUser()
val partitionValue: String = "<partition>" // replace this with a partition key
val config = SyncConfiguration.Builder(user!!, partitionValue)
.build()
val realm: Realm = Realm.getInstance(config)
val address = Address("123 Fake St.", "Springfield", "USA", "90710")
val contact = Contact("Nick Riviera", address)
realm.executeTransaction { transactionRealm ->
transactionRealm.insert(contact)
}
realm.close()
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
Address *address = [[Address alloc] init];
address.street = @"123 Fake St.";
address.city = @"Springfield";
address.country = @"USA";
address.postalCode = @"90710";
Contact *contact = [Contact contactWithName:@"Nick Riviera"];
// Assign the embedded object property
contact.address = address;
[realm addObject:contact];
NSLog(@"Added contact: %@", contact);
}];
// Open the default realm
let realm = try! Realm()
try! realm.write {
let address = Address()
address.street = "123 Fake St"
address.city = "Springfield"
address.country = "USA"
address.postalCode = "90710"
let contact = Person(name: "Nick Riviera", address: address)
realm.add(contact)
}
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

For more information about modeling an embedded object, refer to Define an Embedded Object.

namespace realm {
struct ContactDetails {
// Because ContactDetails is an embedded object, it cannot have its own _id
// It does not have a lifecycle outside of the top-level object
std::string emailAddress;
std::string phoneNumber;
};
REALM_EMBEDDED_SCHEMA(ContactDetails, emailAddress, phoneNumber)
struct Business {
realm::object_id _id;
std::string name;
ContactDetails *contactDetails;
};
REALM_SCHEMA(Business, _id, name, contactDetails)
} // namespace realm
public partial class Address : IEmbeddedObject
{
[MapTo("street")]
public string Street { get; set; }
[MapTo("city")]
public string City { get; set; }
[MapTo("country")]
public string Country { get; set; }
[MapTo("postalCode")]
public string PostalCode { get; set; }
}
public partial class Contact : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; } = ObjectId.GenerateNewId();
[MapTo("_partition")]
public string Partition { get; set; }
[MapTo("name")]
public string Name { get; set; }
[MapTo("address")]
public Address? Address { get; set; } // embed a single address
}
public partial class Business : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; } = ObjectId.GenerateNewId();
[MapTo("_partition")]
public string Partition { get; set; }
[MapTo("name")]
public string Name { get; set; }
[MapTo("addresses")]
public IList<Address> Addresses { get; }
}
// The documentation does not currently have this code example in Dart.
// Please refer to the other languages or related pages for example code.
// Define an embedded object
@RealmClass(embedded = true)
public class Address extends RealmObject {
String street;
String city;
String country;
String postalCode;
public Address(String street, String city, String country, String postalCode) {
this.street = street;
this.city = city;
this.country = country;
this.postalCode = postalCode;
}
public Address() {}
}
// Define an object containing one embedded object
public class Contact extends RealmObject {
@PrimaryKey
private ObjectId _id = new ObjectId();
String name = "";
// Embed a single object.
// Embedded object properties must be marked optional
Address address;
public Contact(String name, Address address) {
this.name = name;
this.address = address;
}
public Contact() {}
}
// Define an object containing an array of embedded objects
public class Business extends RealmObject {
@PrimaryKey
private ObjectId _id = new ObjectId();
String name = "";
// Embed an array of objects
RealmList<Address> addresses = new RealmList<Address>();
public Business(String name, RealmList<Address> addresses) {
this.name = name;
this.addresses = addresses;
}
public Business() {}
}
const AddressSchema = {
name: "Address",
embedded: true, // default: false
properties: {
street: "string?",
city: "string?",
country: "string?",
postalCode: "string?",
},
};
const ContactSchema = {
name: "Contact",
primaryKey: "_id",
properties: {
_id: "objectId",
name: "string",
address: "Address", // Embed a single object
},
};
const BusinessSchema = {
name: "Business",
primaryKey: "_id",
properties: {
_id: "objectId",
name: "string",
addresses: { type: "list", objectType: "Address" }, // Embed an array of objects
},
};
// The documentation does not currently have this code example in Kotlin.
// Please refer to the other languages or related pages for example code.
// Define an embedded object
@RealmClass(embedded = true)
open class Address(
var street: String? = null,
var city: String? = null,
var country: String? = null,
var postalCode: String? = null
): RealmObject() {}
// Define an object containing one embedded object
open class Contact(_name: String = "", _address: Address? = null) : RealmObject() {
@PrimaryKey var _id: ObjectId = ObjectId()
var name: String = _name
// Embed a single object.
// Embedded object properties must be marked optional
var address: Address? = _address
}
// Define an object containing an array of embedded objects
open class Business(_name: String = "", _addresses: RealmList<Address> = RealmList()) : RealmObject() {
@PrimaryKey var _id: ObjectId = ObjectId()
var name: String = _name
// Embed an array of objects
var addresses: RealmList<Address> = _addresses
}
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

Asymmetric objects are write-only. Once inserted, the asymmetric object syncs to Atlas. You cannot access the managed data locally, remove it from the database, or query for it.

For information on how to use asymmetric objects in your application, refer to Stream Data to Atlas.

To create an asymmetric object, initialize an asymmetric object type and add it to the database in a write transaction:

To create an asymmetric object, initialize an asymmetric object type and add it to the database in a write transaction:

Once you have an open database, you can create an asymmetric object inside a write transaction. Pass your object data to realm.ingest.

Data Ingest is not supported in the Java SDK. To stream data from the client application to Atlas, use the Kotlin SDK.

To create an asymmetric object, initialize an asymmetric object type and add it to the database in a write transaction:

Unlike other SDK objects, you do not use the copyToRealm() method to create it. Instead, you use a special insert() extension method to insert it into the database.

To create a new AsymmetricRealmObject instance, instantiate a new object of an asymmetric object type using insert().

In the following example, we instantiate a new WeatherSensor object and pass it to insert() within a write transaction:

New in version 1.10.0.

Data Ingest is not supported in the Java SDK. To stream data from the client application to Atlas, use the Kotlin SDK.

To create an asymmetric object, initialize an asymmetric object type and add it to the database in a write transaction:

To create an asymmetric object, initialize an asymmetric object type and add it to the database in a write transaction:

To create an asymmetric object, initialize an asymmetric object type and add it to the database in a write transaction:

auto weatherSensorReading =
realm::WeatherSensorReading{.deviceId = "WX1278UIT",
.temperatureInFahrenheit = 64.7,
.windSpeedInMph = 7};
realm.write([&] { realm.add(std::move(weatherSensorReading)); });
// The documentation does not currently have this code example in C#.
// Please refer to the other languages or related pages for example code.
realm.write(() {
realm.ingest(
WeatherSensor(weatherSensorId, "WX1278UIT", 66.7, 29.65, 2));
});
// The Java SDK does not support this API.
// The documentation does not currently have this code example in JavaScript.
// Please refer to the other languages or related pages for example code.
// Open a write transaction
realm.write {
// Create a new asymmetric object
val weatherSensor = WeatherSensor().apply {
deviceId = "WX1278UIT"
temperatureInFarenheit = 6.7F
barometricPressureInHg = 29.65F
windSpeedInMph = 2
}
// Insert the object into the realm with the insert() extension method
insert(weatherSensor)
// WeatherSensor object is inserted into the realm, then synced to the
// App Services backend. You CANNOT access the object locally because it's
// deleted from the local realm after sync is complete.
}
// The Java SDK does not support this API.
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
@MainActor
func useRealm(_ asymmetricRealm: Realm, _ user: User) async {
try! asymmetricRealm.write {
asymmetricRealm.create(WeatherSensor.self,
value: [ "_id": ObjectId.generate(),
"deviceId": "WX1278UIT",
"temperatureInFahrenheit": 66.7,
"barometricPressureInHg": 29.65,
"windSpeedInMph": 2
])
}
}
realm.write(() => {
realm.create(WeatherSensor, {
_id: new BSON.objectId(),
deviceId: "WX1278UIT",
temperatureInFahrenheit: 66.7,
barometricPressureInHg: 29.65,
windSpeedInMph: 2,
});
});

For more information about modeling an asymmetric object, refer to Define an Asymmetric Object.

struct WeatherSensorReading {
realm::primary_key<realm::object_id> _id{realm::object_id::generate()};
std::string deviceId;
double temperatureInFahrenheit;
int64_t windSpeedInMph;
};
REALM_ASYMMETRIC_SCHEMA(WeatherSensorReading, _id, deviceId,
temperatureInFahrenheit, windSpeedInMph)
// The documentation does not currently have this code example in C#.
// Please refer to the other languages or related pages for example code.
@RealmModel(ObjectType.asymmetricObject)
class _WeatherSensor {
@PrimaryKey()
@MapTo("_id")
late ObjectId id;
late String deviceId;
late double modtemperatureInFahrenheitel;
late double barometricPressureInHg;
late double windSpeedInMph;
}
// The Java SDK does not support this API.
class WeatherSensor extends Realm.Object {
static schema = {
name: "WeatherSensor",
// Sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: "_id",
properties: {
_id: "objectId",
deviceId: "string",
temperatureInFahrenheit: "int",
barometricPressureInHg: "float",
windSpeedInMph: "float",
},
};
}
// Implements the `AsymmetricRealmObject` interface
class WeatherSensor : AsymmetricRealmObject {
@PersistedName("_id")
@PrimaryKey
var id: ObjectId = ObjectId()
var deviceId: String = ""
var temperatureInFarenheit: Float = 0.0F
var barometricPressureInHg: Float = 0.0F
var windSpeedInMph: Int = 0
}
// The Java SDK does not support this API.
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
class WeatherSensor: AsymmetricObject {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var deviceId: String
@Persisted var temperatureInFahrenheit: Float
@Persisted var barometricPressureInHg: Float
@Persisted var windSpeedInMph: Int
}
class WeatherSensor extends Realm.Object<WeatherSensor> {
_id!: Realm.BSON.ObjectId;
deviceId!: string;
temperatureInFahrenheit!: number;
barometricPressureInHg!: number;
windSpeedInMph!: number;
static schema: ObjectSchema = {
name: "WeatherSensor",
// sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: "_id",
properties: {
_id: "objectId",
deviceId: "string",
temperatureInFahrenheit: "int",
barometricPressureInHg: "float",
windSpeedInMph: "float",
},
};
}

After you define a geospatial object type, you can use that type to create objects that persist geospatial data.

Initialize objects that use the geospatial data class, and add them to the database like you would any other object type.

The C++ SDK does not currently support geospatial data.

The Java SDK does not support geospatial data. To store and query geospatial data, use the Kotlin SDK.

However, in this example, because the MyGeoPoint class does not extend Realm.Object, we must specify MyGeoPoint.schema when opening the database:

The Java SDK does not support geospatial data. To store and query geospatial data, use the Kotlin SDK.

However, in this example, because the MyGeoPoint class does not extend Realm.Object, we must specify MyGeoPoint.schema when opening the database:

// The C++ SDK does not currently support this API.
realm.WriteAsync(() =>
{
realm.Add(new Company
{
Location = new CustomGeoPoint(47.68, -122.35)
});
realm.Add(new Company
{
Location = new CustomGeoPoint(47.9, -121.85)
});
});
final realm =
Realm(Configuration.local([MyGeoPoint.schema, Company.schema]));
realm.write(() {
realm.addAll([
Company(
firstCompanyID,
location: MyGeoPoint(coordinates: [-122.35, 47.68]),
),
Company(
secondCompanyID,
location: MyGeoPoint(coordinates: [-121.85, 47.9]),
)
]);
});
// The Java SDK does not support this API.
const realm = await Realm.open({
// `MyGeoPoint` does not extend `Realm.Object`, so you pass
// only the `.schema` when opening the realm.
schema: [Company, MyGeoPoint.schema],
});
// Add geospatial object to realm.
realm.write(() => {
realm.create(Company, {
_id: 6,
location: new MyGeoPoint(-122.35, 47.68),
});
realm.create(Company, {
_id: 9,
location: new MyGeoPoint(-121.85, 47.9),
});
});
realm.writeBlocking {
copyToRealm(
Company().apply {
location = CustomGeoPoint(47.68, -122.35)
}
)
copyToRealm(
Company().apply {
location = CustomGeoPoint(47.9, -121.85)
}
)
}
// The Java SDK does not support this API.
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift.
// Please refer to the other languages or related pages for example code.
const realm = await Realm.open({
// `MyGeoPoint` does not extend `Realm.Object`, so you pass
// only the `.schema` when opening the realm.
schema: [Company, MyGeoPoint.schema],
});
// Add geospatial object to realm.
realm.write(() => {
realm.create(Company, {
_id: 6,
location: new MyGeoPoint(-122.35, 47.68),
});
realm.create(Company, {
_id: 9,
location: new MyGeoPoint(-121.85, 47.9),
});
});

The following image shows the results of creating these two company objects:

2 GeoPoints
click to enlarge

For more information about modeling a geospatial object, refer to Define a Geospatial Object.

// The C++ SDK does not currently support this API.
public partial class Company : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public Guid Id { get; private set; } = Guid.NewGuid();
public CustomGeoPoint? Location { get; set; }
public Company() { }
}
// Use the GeoJSON-compatible class as a property in your model.
@RealmModel()
class _Company {
@PrimaryKey()
late ObjectId id;
_MyGeoPoint? location;
}
// The Java SDK does not support this API.
class Company extends Realm.Object {
static schema = {
name: "Company",
properties: {
_id: "int",
location: "MyGeoPoint",
},
primaryKey: "_id",
};
}
class Company : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var location: CustomGeoPoint? = null
}
// The Java SDK does not support this API.
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
class CustomGeoPoint: EmbeddedObject {
@Persisted private var type: String = "Point"
@Persisted private var coordinates: List<Double>
public var latitude: Double { return coordinates[1] }
public var longitude: Double { return coordinates[0] }
convenience init(_ latitude: Double, _ longitude: Double) {
self.init()
// Longitude comes first in the coordinates array of a GeoJson document
coordinates.append(objectsIn: [longitude, latitude])
}
}
class Company extends Realm.Object<Company> {
_id!: number;
location!: MyGeoPoint;
static schema: ObjectSchema = {
name: "Company",
properties: {
_id: "int",
location: "MyGeoPoint",
},
primaryKey: "_id",
};
}

Back

Create

Next

Create Properties