Creating multiple documents and setting custom id

Hi, total beginner here.

Trying to migrate data into Fauna and keep the existing id. The following request creates a 400 error.
I can create single users OK so I guess it has to do with setting the id…

client.query(
        q.Map( data,
          q.Lambda('user', 
              q.Create( q.Ref(q.Collection('users'), q.Var('user').id ), { data: q.Var('user') }, )
         ),
     )
  )

Thanks in advance for your help.

Hi @McFly,

Since data in your query is likely and array with the document id and the actual document data, you will need to select it from the array.

As an example - if I have something like this as my userData

["101",{firstName:'George',lastName:'Washington'}]

then my query looks like

client.query(
q.Map(userData,
        q.Lambda('uData',
        q.Create(q.Ref(q.Collection('users'),q.Select(0,Var('uData'))),
        { data: q.Select(1,Var('uData')) }
        )
    )
)
              

Select() will extract the item in position 0 and 1, which in this case are the documentId and data respectively.

Alternately, you can also pass the userData as an array of parameters to Lambda itself, like so -

q.Map(userData,
         q.Lambda(["dID","data"],
         q.Create(q.Ref(q.Collection('users'),Var("dID")),
         {data: Var("data")}
        )
     )
  )
               

Hope that helps!

1 Like

Thanks for this example. In my case, the user data does not come in the format described. It is not an array, but an object.
So this is the solution that worked for me:

client.query(
        q.Map(data,
            q.Lambda('uData',
                q.Create(q.Ref(q.Collection('users2'),q.Select('id',q.Var('uData'))), 
                { data: q.Var('uData') }
                )
            )
        )
    )

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