ChangJoo Park
ChangJoo Park

Reputation: 979

Find object by realm.js

Hello I use realm database with react-native.

I have Item schema and find one item by id.

var items = realm.objects('Item');
var item = items.filtered('id == $0', item_id);
console.log(item.name); // It should be printed name, but undefined

I can't find item. so use lodash.

var item = _.find(realm.objects('Item'), _.matchesProperty('id', item_id));
console.log(item.name); // print "ABCD"

How do I get item by id?

Upvotes: 7

Views: 7596

Answers (3)

Zanyar Jalal
Zanyar Jalal

Reputation: 1874

you can use objectForPrimaryKey function but must set primaryKey you schema

Set primarykey

const BookSchema = {
  name: 'Book',
  primaryKey: 'id',
  properties: {
    id:    'int',    // primary key
    title: 'string',
    price: 'float'
  }
};

Usage

const findObject = realm.objectForPrimaryKey('Item', item_id);

Upvotes: 0

Josh Parrett
Josh Parrett

Reputation: 89

realm.objectForPrimaryKey('Item', item_id)

Upvotes: 2

Ari
Ari

Reputation: 1447

filtered returns a Results object which is very similar to a javascript Array.

So your code should be:

var items = realm.objects('Item').filtered('id == $0', item_id);
var item = items[0];
console.log(item.name); // should print the name

Upvotes: 12

Related Questions