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:

https://docs.mongodb.com/manual/reference/operator/update/push/

Let me know if that helps.

Best
Pavel

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?

https://docs.mongodb.com/realm-sdks/js/latest/Realm.List.html#push

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.