Reputation: 85
I am trying to create a realm database with items nested inside containers. This would operate like a standard filesystem, where containers can have both items and other containers inside them. How can I create this type of structure? I have set up these schemas:
const ItemSchema = {
name: 'Item',
primaryKey: 'id',
properties: {
id: {type: 'string', indexed: true},
title: 'string',
createdAt: 'date',
updatedAt: 'date',
picture: {type: 'data', optional: true},
parent: {type: 'Container', optional: true},
}
};
const ContainerSchema = {
name: 'Container',
primaryKey: 'id',
properties: {
id: {type:'string', indexed:true},
title: 'string',
createdAt: 'date',
updatedAt: 'date',
parent: {type: 'Container', optional: true},
childContainers: {type: 'list', objectType: 'Container'},
childItems: {type: 'list', objectType: 'Item'},
}
};
I also set up this model for Items, but haven't created one for Containers yet:
class ItemModel {
constructor(title, children) {
this.id = Utils.guid();
this.title = title;
this.children = children;
this.createdAt = new Date();
this.updatedAt = new Date();
}
}
Now how do I actually populate a database and assign parents and children to existing items? I know I have to do this to create an item:
let item = new ItemModel('testItem')
db.write(() => {
item.updatedAt = new Date();
db.create('Item', item);
})
But I don't know where I go after that. the realm docs give this example:
carList.push({make: 'Honda', model: 'Accord', miles: 100});
but once I create a container with db.create
, how do I then add an existing item as its child (not declare a new item as the docs show)?
Upvotes: 0
Views: 379
Reputation: 526
After you have created the item you can use push()
to add it to the list in the container.
Assuming you already have the container, the code could look something like this:
let item = new ItemModel('testItem')
db.write(() => {
item.updatedAt = new Date();
var item = db.create('Item', item);
container.childItems.push(item);
});
Upvotes: 1