Error updating object in React Native Realm

Hi,

I’m having trouble updating a Realm object in React Native Realm. I’m querying for the object, able to console.log the object, but once I try to update the object by setting one of its keys, I get this error:

Attempting to create an object of type ‘[OBJECT]’ with an existing primary key value ‘5f76395eeca29f5aeb466873’

I’m particularly confused because I’m able to successfully update an object using that pattern (querying then mutating) in a different component.

Any idea what could be going on here?

Thanks!

@Jerry_Wang You cannot change primary keys once set - if you want to do that you should delete the object and then recreate a new one with the primary key you want.

I’m not attempting to change the primary key, though.

It seems as though my mutation (of properties other than the primary key) is being interpreted as a creation request.

You said key - so I assumed primary key. What are you attempting to do then?

Sorry, I should’ve been more specific.

Here’s an example:

Realm object:
{ _id: “fkl2j3”, “username”: “Jerry”, “description”: “a developer” }

I’m trying to update the description with:
realm.write( () => { realmObject.description = “a React Native developer” } )

@Jerry_Wang I believe you either need to use the upsert method with “modified” parameter passed -

Or realmObject in your code snippet is actually a realm result and you need to get the actual indice of the object you are trying to update, as in - realmObject[0]

Interesting. Okay. I’ve checked to make share that I’m modifying the object (and not the Realm result).

Any idea why updating some properties requires upsert while some properties can be directly modified?

For my particular usecase, I’m able to modify “description” directly, but not “updatedAt”

Realm object:
{ _id: “fkl2j3”, “username”: “Jerry”, “description”: “a developer”, updatedAt: null }

Works:
realm.write( () => { realmObject.description = “a React Native developer” } )

Doesn’t work (throws primary key error):
realm.write( () => { realmObject.updatedAt = “Fri, 25 Sep 2020 02:39:28 GMT"” } )

@Ian_Ward

It looks like upserting gives me the same error. Are there logs I can find beyond the ones provided by the Realm console that would help me debug what’s going on further?

realmObject.updatedAt = "Fri, 25 Sep 2020 02:39:28 GMT" will not work since updateAt isn’t a string. realmObject.updatedAt = new Date("Fri, 25 Sep 2020 02:39:28 GMT") is better.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.