node.js - Realm 与关系读取数据

标签 node.js mongodb vue.js electron realm

我正在研究 Realm ,以使其在Electron中作为本地db脱机工作。现在,我想进行join(aggregation),因此我定义了两个架构之间的关系,但随后数据未同步。寻求帮助会很棒。
这是我的架构:

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
我想查询并获取文章结果,并且在文章模式中,我们定义了一个键'article_meta'和objectId。现在,我希望获取具有以article_meta作为对象的所有属性的article结果,该对象基于(article.article_meta = articlemeta._id)
预期结果:
[{ _id: '1', catalog_id: '', content: '', createdAt: '', main_image_url: '', origin_type: '', pub_date: '', publication: '', sub_title: '', title: '', updatedAt: '', url: '', article_meta: {} }, {..}, {..}]

最佳答案

Realm 对象可以通过点表示法引用“已加入”的 Realm 对象。来自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.


因此,例如,一个Person对象有一个Dog对象作为它的属性之一,而您想获得该pesons的狗的名字。
让我们通过他们的_id来找到一个特定的人
const person = realm.objectForPrimaryKey("Person", 1234)
如果我们那么想要人狗的名字
const dogName = person.dog.dog_name
在您的情况下,您可以获取特定的文章,然后使用点符号访问所有articlemeta属性。
const article = realm.objectForPrimaryKey("article", 1234)
然后通过点表示法访问其余的属性
const id = article._id
const catalogId = article.catalog_id
const mainImageUrl = article.article_meta.main_image_url
如您所见,由于Realm对象知道它们自己的子属性,因此可以通过点表示法进行访问(在此示例中),而无需查询。

关于node.js - Realm 与关系读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66558599/

相关文章:

vue.js - 当使用 Vuejs 响应类型为 blob 时,如何处理错误?

javascript - 如何在 sequelize 迁移中使用 insert()?

node.js - ExcelJS 的 writeBuffer 不返回 Buffer 类型

javascript - 关联数组中的双索引

javascript - 如何通过 Meteor.js 模板传播数据库 ID?

mongodb - 如何将属性添加到数组中的对象(包含对象)?

node.js - 如何测量 Nodejs 中的事件循环阻塞?

mongodb - 撤消mongodb中的删除操作

javascript - 如何在Vue中捕获 Canvas 上的关键事件

html - Bootstrap 阴影未显示在 nav.shadow 上