【问题标题】:Realm.js: Storing unstructured object as propertyRealm.js:将非结构化对象存储为属性
【发布时间】:2016-07-21 13:50:37
【问题描述】:

我们有一个内容交付应用程序,我们可以在其中将结构上动态的 JSON 对象放入其中。 React Native 使用 JSON,并从这些对象构建用户界面。

这是我现在正在使用的架构:

const CardSchema = {
    name: 'Card',
    properties: {
        id: 'string',
        cardSubType: 'string',
        cardType: 'string',
        state: 'string',
        contentType: 'string',
        context: {},
    },
};

字段context 是动态部分。它基本上是一个可以有任意数量的字段的对象。我们在编译时不知道那里有哪些字段。

我们希望使用 realm.js 来持久化我们的数据,因为它既好又快,而且我们可以在编译时模块 99% 的对象。

我们想要存储任何对象的只是这个字段(以及其他几个字段)。

Realm for React Native 可以做到这一点吗?或者我是否需要将其建模为字符串并在存储时进行序列化,在加载时进行反序列化?

【问题讨论】:

    标签: react-native realm


    【解决方案1】:

    Realm 还不支持存储字典/动态对象。这绝对是路线图上的内容,因为能够简单地存储和检索 JSON 对象是很自然的。在完全支持字典之前,您要么需要按照建议将数据存储为字符串,要么创建自己的 JSON 模型。类似的东西

    const UNDEFINEDTYPE = 0;
    const INTTYPE = 1;
    const STRINGTYPE = 2;
    
    const JSONValueSchema = {
        name: 'JSONValue',
        properties: {
            type: 'int',
            stringValue: { type: 'string', optional: true },
            intValue:    { type: 'int', optional: true },
            jsonValue:   { type: 'JSON', optional: true },        
        }
    };
    
    const JSONEntrySchema = {
        name: 'JSONEntry',
        properties: {
            key: 'string',
            value: 'string'
        }
    };
    
    const JSONSchema = {
        name: 'JSON',
        properties: {
            entries: { type: 'list', objectType: 'JSONEntry' }
        }
    }
    

    这样做会有点冗长,但它可以让您完全使用带有 keyPath 查询的查询系统,其中存储 JSON blob 会迫使您使用 CONTAINS 查询。不确定所有的努力对于您的应用程序是否值得。

    【讨论】:

    • 谢谢。总的来说,我认为这种努力是合理的,因为我们希望存储具有多个索引的文档以提高查询性能。因此,我们可能会将整个文档存储为序列化字符串,并将我们想要索引的字段推断为属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多