I’m new to realm. How can I filter a nested schema in React Native Realm? I’m just trying to do it with Realm query. I can already handle this with javascript.
Models:
const ModelA = {
name: "ModelA",
primaryKey: "id",
properties: {
id: "objectId",
name: "string",
data: "ModelB[]"
}
};
const ModelB = {
name: "ModelB",
properties: {
label: "int",
text: "string"
}
};
I have such data.
[
{
"id": "6407d4949096750f578c536c",
"name": "name1",
"data": [
{ "label": "1", "text": "text1" },
{ "label": "1", "text": "text2" },
{ "label": "2", "text": "text3" },
{ "label": "2", "text": "text4" },
]
},
{
"id": "7407d4949096750f578c536c",
"name": "name2",
"data": [
{ "label": "1", "text": "text1" },
{ "label": "2", "text": "text2" },
{ "label": "2", "text": "text3" },
{ "label": "2", "text": "text4" },
]
}
]
Here I want to filter and list like label == 1. Just like in this example. How can I do that?
let list = realm.objects("ModelA").filtered(/* ? */);
console.log(JSON.stringify(list));
Console output:
[
{
"id": "6407d4949096750f578c536c",
"name": "name1",
"data": [
{ "label": "1", "text": "text1" },
{ "label": "1", "text": "text2" },
]
},
{
"id": "7407d4949096750f578c536c",
"name": "name2",
"data": [
{ "label": "1", "text": "text1" },
]
},
]
2
Answers
following the documentation and tutorial-query-language
you should be able to filter it using
filtered
.that would be like:
Restating the question: There are two objects in Realm; ModelA and ModelB
ModelA has a List property
data
containing ModelB objectsModelB has
label
propertyThe objective is to query ModelA objects for any that have a ModelB list of
data
wherelabel
property == 1Here’s the query
When that query is run against the original data, the output matches the output in the question, for the top level objects
Keeping in mind that since we are querying on the top ModelA objects, those entire objects are returned. Filtering is only 1 level deep, and returns the entire object e.g. it won’t filter out related objects, that would either require additional in-code filtering or reversing how the filter is done; filter on the ModelB objects that are related to ModelA objects.