How to insert a document reference into a List using splice?

Hi, I’m struggling to understand how to properly insert a document reference into a List using splice, haven’t found any clear examples in the documentation.

I’m able to achieve this when the document being inserted doesn’t exist yet (and needs to be created at this step), but when I try to add an existing document’s reference to the List, it fails.

Is there a simple solution to this? Thanks :slight_smile:

Hi @Cameron_Cruz,

I think what you are looking for is $push or $addToSet in an update:

Let me know if that helps.


Hi @Pavel_Duchovny, thanks for your suggestion.

Looking at the following docs, it doesn’t look like .push allows me to specify the index to insert at?

I’d like to do something like the following:

realm.write(() => {
    realmObj.someList.splice(index, 0, { _id: existingObjectId, })

where someList is an array of document references, but this fails when there’s already an object with that id in Realm.

Hey, I’m trying to use splice in order to swap order position in a Realm.List property but nothing happens.

Here’s a code example of what I’m trying to do:

const list = useObject(MyList)
const swap = (from, to) => 
	list.arr.splice(from, 1, list.arr.splice(to, 1, list.arr[from])[0]);

It seems the code above fails silently and can’t make the swap. I noticed that the second splice does not return anything, so is there a bug in Realm or what is the efficient and correct way to do this kind of swap position?