How to add a nested List of objects in Realm “Error: JS value must be of type: object”

青春壹個敷衍的年華 提交于 2019-12-06 15:33:46

问题


I'm trying to create Realm database that has a json array of objects with a nested array of objects.

When I try to add using the code below I always get the error: JS value must be of type: object.

Schemas:

import Realm from 'realm';

class Exercise extends Realm.Object {
}
Exercise.schema = {
    name: 'Exercise',
    primaryKey: 'id',
    properties: {
        id: 'int',
        name: 'string',
        category: 'string',
        bodyPart: 'string',
        levels: {type: 'list', objectType: 'Level'}
    }
};

class Level extends Realm.Object {
}
Level.schema = {
    name: 'Level',
    properties: {
        level: 'int',
        equipments: 'string'
    }
};

export default new Realm({schema: [Exercise, Level, Multiplier]});

and the method where I'm trying to create the database:

 realm.write(() => {
        let exercise = realm.create('Exercise', {
            id: 209,
            name: 'Dumbbell Overhead Press',
            category: 'Military Press',
            bodyPart: 'Shoulder'
        }, true);

        exercise.levels.push({
            level: 3,
            equipments: 'DB'
        });

    });

I tried every way possible, putting the array direct in the Exercise creation, etc, I had no success..

Cheers


回答1:


U have to specify the index of the record. As exercise.returns a record not an exercise object

try this instead

realm.write(() => {
    let exercise = realm.create('Exercise', {
        id: 209,
        name: 'Dumbbell Overhead Press',
        category: 'Military Press',
        bodyPart: 'Shoulder'
    }, true);
    exercise[0].levels.push({
        level: 3,
        equipments: 'DB'
    });

});


来源:https://stackoverflow.com/questions/38214973/how-to-add-a-nested-list-of-objects-in-realm-error-js-value-must-be-of-type-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!