I’m trying to create a custom function (on javascript side), called createIfNotExists
, what it will do is either create the document OR return the already existing document.
I’m trying to do this:
Let(
{
existingDocument: Get(Match(Index('userByEmail'), 'test@email'))
},
If(
Not(IsNull(Var('existingDocument'))),
Var('existingDocument'),
Create(Collection('users'), { data })
)
)
Which only does 1 read if the document already exists (1 for Get
function); I can’t do this because Get
will throw instance not found
exception. I wanted it to return null
if the document does not exist.
I’m left with no choice but to do:
If(
Exists(Match(Index("userByEmail"), "email@email.com")),
Get(Match(Index("userByEmail"), "email@email.com")),
Create(Collection('myCollection'), { data })
)
Which does 2 reads if the document already exists (1 read for Exists
function, and another for Get
function) essentially making it O(2n)
instead of just O(n)
. So if I run this 100,000 times, that converts to 200,000 reads if all documents already exist.