Insert multiple entries with Map/Do/Lambda

Hi, I’m new to FQL and I’m trying to insert data to a collection in batches but I can’t figure out how to make my query work, any advise will be apreciated.

Map(
      [
        ["123", "Prod1", "25.3", "10"],
        ["124", "Prod2", "16.22", "20"],
        ["125", "Prod3", "9.65", "100"]
      ],
      Do(
        Lambda(
           ["id", "name", "price", "stock"],
           Create(Ref(Collection("products"), "id"), {
               data: { name: Var("name"), price: Var("price"), stock: Var("stock") }
          })
        )
      )
    )

You used "id" instead of Var("id"). Fauna doesn’t support document IDs that are not string-encoded numbers.

Also, the Do() function is unnecessary.

Here’s the working query:

Map(
  [
    ["123", "Prod1", "25.3", "10"],
    ["124", "Prod2", "16.22", "20"],
    ["125", "Prod3", "9.65", "100"]
  ],
  Lambda(
    ["id", "name", "price", "stock"],
    Create(Ref(Collection("products"), Var("id")), {
      data: { name: Var("name"), price: Var("price"), stock: Var("stock") }
    })
  )
)

and the result from my test:

[
  {
    ref: Ref(Collection("products"), "123"),
    ts: 1615587171540000,
    data: { name: 'Prod1', price: '25.3', stock: '10' }
  },
  {
    ref: Ref(Collection("products"), "124"),
    ts: 1615587171540000,
    data: { name: 'Prod2', price: '16.22', stock: '20' }
  },
  {
    ref: Ref(Collection("products"), "125"),
    ts: 1615587171540000,
    data: { name: 'Prod3', price: '9.65', stock: '100' }
  }
]

Fantastic!

I now see I missed the Var(“id”) part in the document Ref, I only had put “id” :man_facepalming:

One more thing, If I want to update the same entries in the future, would the Update keyword instead of the Create do the work?

BTW, Do you think this query could handle over a 5000 entries at once? or should I split it?

Yes, a Lambda that uses Update would work just fine.

Provided that your queries fit within the transaction limits, you can create/update/delete as many documents in one transaction as you like: Documents | Fauna Documentation

1 Like