Realm React Native - 如何分配对象属性类型

时间:2016-11-23 02:52:19

标签: react-native realm

我有2个领域数据模型。 'Foods'模型有一个对象属性类型'foodRating',它旨在成为FoodsRatings模型的链接。

class FoodRatings extends Realm.Object {}
FoodRatings.schema = {
  name: 'FoodRatings',
  primaryKey: 'foodRatingId',
  properties: {
    foodRatingId: { type: 'int', indexed: true },
    name: 'string',
  }
}; 


class Foods extends Realm.Object {}
Foods.schema = {
  name: 'Foods',
  primaryKey: 'foodId',
  properties: {
    foodId: { type: 'int', indexed: true },
    name: 'string',
    foodRating: {type: 'FoodRatings'},
  }
}; 

FoodRatings预先填充了许多行,这些行旨在保持静态且不变。您可以通过FoodRatings中的一个选项为食物分配foodRating。

我遇到的问题是,当我尝试创建一个新的Foods对象并将'foodRating'属性指定为FoodRatings对象时,它会中断。

foodRatings = realm.objects('FoodRatings')
let foodRating = foodRatings.filtered('foodRatingId = 1');
realm.write(() => {
   realm.create('Foods', {foodId: 1, name: 'apples', foodRating: foodRating[0]});
})

我看到很多关于'链接'的讨论,但还没有为realm js发布。所有示例和文档都假设新条目而不是您尝试分配给模型的现有对象。

知道我该怎么做吗?

2 个答案:

答案 0 :(得分:1)

免责声明 - 我正在使用Realm Swift并且从未使用过Realm React Native。

话虽如此,从文档中可以看出,foodRating的定义是错误的。我想它应该像示例

cars:    {type: 'list', objectType: 'Car'}

即。

foodRating: {type: 'list', objectType: 'FoodRatings'}

“链接”存在于Realm Swift中,但在您的情况下可能会用于将食品评级与所有具有该评级的食品联系起来。所以我认为它解决了一个不同的问题。

答案 1 :(得分:1)

你到底看到了什么错误?

你的例子对我有用

Trip.aggregate([
    { "$unwind": "$expenses" },
    {
        "$group": {
            "_id": "$_id",
            "totalCost": { "$sum": "$expenses.cost" },
            "expenses": { "$push": "$expenses" }
        }
    },
    { 
        "$match": { 
            "totalCost": {
                "$gte": minCost,
                "$lte": maxCost
            }
        }
    }           
]).exec(callback);