I'm working on realm to make it work offline as local db in Electron. Now I want to make join(aggregation), so I defined a relationship between two schema's but then the data is not getting synced. It would be great to get help.
Here's my schema:
const articleMetaSchema = {
name: 'articlemeta',
properties: {
_id: 'objectId?',
catalog_id: 'objectId?',
content: 'objectId?',
createdAt: 'date?',
description: 'string?',
main_image_url: 'string?',
origin_type: 'string?',
pub_date: 'date?',
publication: 'objectId?',
sub_title: 'string?',
title: 'string?',
updatedAt: 'date?',
url: 'string?'
},
primaryKey: '_id'
}
const articleSchema = {
name: 'article',
properties: {
_id: 'objectId?',
active_search: 'bool?',
article_meta: 'articlemeta?',
catalog_id: 'objectId?',
content: 'objectId?',
createdAt: 'date?',
flagged: 'bool?',
owner_id: 'objectId?',
rating: 'int?',
read: 'bool?',
status: 'string?',
status_updated_at: 'date?',
updatedAt: 'date?'
},
primaryKey: '_id'
}
config = {
schema,
path: getDBPath(),
sync: {
user: app.currentUser,
partitionValue: new ObjectID(getCatalogId()),
error: (error) => {
console.log(error.name, error.message)
}
}
}
let realm = await Realm.open(config)
// query
I want to query and get the article result and in article schema we have defined a key 'article_meta' which is and objectId. Now I want article result with all the properties with article_meta as an object fetched on the basis of (article.article_meta = articlemeta._id)
Expected result:
[{ _id: '1', catalog_id: '', content: '', createdAt: '', main_image_url: '', origin_type: '', pub_date: '', publication: '', sub_title: '', title: '', updatedAt: '', url: '', article_meta: {} }, {..}, {..}]
Realm objects can reference 'joined' realm objects via dot notation. from the docs
Filter on Related and Embedded Object Properties
To filter a query based on a property of an embedded object or a related object, use dot-notation as if it were in a regular, nested object.
So for example, a Person object has a Dog object as one of it's properties and you want to get that pesons' dogs name.
Let's get a specific person by their _id
const person = realm.objectForPrimaryKey("Person", 1234)
if we then want the persons dogs name
const dogName = person.dog.dog_name
In your case you can get a specific article, and then access all of the articlemeta properties using dot notation
const article = realm.objectForPrimaryKey("article", 1234)
and then access the rest of the properties through dot notiation
const id = article._id
const catalogId = article.catalog_id
const mainImageUrl = article.article_meta.main_image_url
As you can see, a query is not needed (for this example) as the Realm objects know their own child properties and can be accessed via dot notation.