0

I'm using Mongodb Realm. I know it is possible to 'createOrUpdate' in realm by using the primary key i.e If the primary key doesn't exists create a new object, If it does update the object.

Something like

realm.write(() => {
  // Create a book object
  realm.create('Book', {id: 1, date: '12-12-2020', price: 35});

  // It will update the price but won't create a new object since the id is the same
  realm.create('Book', {id: 1, date: '12-12-2020', price: 55}, 'modified');
});

The realm docs says that

If your model class includes a primary key, you can have Realm intelligently update or add objects based off of their primary key values. This is done by passing true as the third argument to the create method:

this can be found here https://docs.mongodb.com/realm-legacy/docs/javascript/latest/#creating-and-updating-objects-with-primary-keys

NOW, I want to update the Object based on a different field(key) apart from the primary key and On this case it is the date field This is to say that, If the date doesn't exist, create a new object/entry but it it does, just update the price.

How do I do this with realm?

Amani
  • 227
  • 1
  • 10
  • 1
    Those are the old docs btw. Let me state this - *if* you know an objects primary key, you can use that to 'point' to the object you want to update; and you can update any of it's properties without getting the object first. However, if you don't know the primary key, or it doesn't have one the object has to be retrieved first, and then within a write transaction any of its properties can be updated. e.g. if I know I want to update object with id '1' then you can simply reference '1' in the create and it will be updated if it exists or created if not. It does require that primary key. – Jay Jul 11 '21 at 15:20
  • 2
    This question is really hard to answer considering how little we know of your project: How do you handle multiple objects with the same date? Which one would you update in that instance? Or would you use a combinantion of the PK and the date to fetch the right one? If you have the PK already what Jay said is the way. If you only have a date, quering realm for that date may give you multiple records. That looks like a problem to me. – Andrea Catalini Jul 12 '21 at 09:43
  • @AndreaCatalini Objects should NOT have multiple dates IN THE FIRST PLACE because if the date is already there, it should UPDATE and not create another entry of the same date. – Amani Jul 21 '21 at 05:51
  • @Jay and AndreaCatalini... I get the point that I should first fetch the object and If i find it, update it and if i dont find it then I should create it. When asking initially, I thought maybe realm had some sort of 'out of the box' createOrUpdate method. – Amani Jul 21 '21 at 05:54

0 Answers0