Create a document in a collection

Problem

You need to create a document in an existing collection in the current database.

Solution

Use the Create function:

try
{
    Value result = await client.Query(
        Create(
            Collection("dilapidated_huts"),
            Obj("data", Obj("material", "straw"))
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(ref: RefV(id = "300222988909806080", collection = RefV(id = "dilapidated_huts", collection = RefV(id = "collections"))),ts: LongV(1622573803740000),data: ObjectV(material: StringV(straw)))
result, err := client.Query(
	f.Create(
		f.Collection("dilapidated_huts"),
		f.Obj{"data": f.Obj{"material": "straw"}},
	))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[data:map[material:straw] ref:{300223005074653696 0xc000180570 0xc000180570 <nil>} ts:1622573819180000]
System.out.println(
    client.query(
        Create(
            Collection("dilapidated_huts"),
            Obj("data", Obj("material", Value("straw")))
        )
    ).get());
{ref: ref(id = "300223068194734592", collection = ref(id = "dilapidated_huts", collection = ref(id = "collections"))), ts: 1622573879370000, data: {material: "straw"}}
client.query(
  q.Create(
    q.Collection('dilapidated_huts'),
    { data: { material: 'straw' } }
  )
)
.then((ret) => console.log(ret))
.catch((err) => console.error('Error: %s', err))
{
  ref: Ref(Collection("dilapidated_huts"), "300223085354680832"),
  ts: 1622573895720000,
  data: { material: 'straw' }
}
result = client.query(
  q.create(
    q.collection("dilapidated_huts"),
    {"data": {"material": "straw"}}
  )
)
print(result)
{'ref': Ref(id=300223090590220800, collection=Ref(id=dilapidated_huts, collection=Ref(id=collections))), 'ts': 1622573900720000, 'data': {'material': 'straw'}}
try {
  println(Await.result(
    client.query(
      Create(
        Collection("dilapidated_huts"),
        Obj("data" -> Obj("material" -> "straw"))
      )
    ),
    5.seconds
  ))
} catch {
  case unknown: Throwable => println("Error: " + unknown.getMessage())
}
{ref: ref(id = "300223310993555968", collection = ref(id = "dilapidated_huts", collection = ref(id = "collections"))), ts: 1622574110890000, data: {material: "straw"}}
Create(
  Collection('dilapidated_huts'),
  { data: { material: 'straw' } }
)
{
  ref: Ref(Collection("dilapidated_huts"), "302044124774662656"),
  ts: 1624310574250000,
  data: { material: 'straw' }
}

Discussion

The Create function needs both the Reference to a collection and the document’s data.

Was this article helpful?

We're sorry to hear that.
Tell us how we can improve!
Visit Fauna's Discourse forums or email docs@fauna.com

Thank you for your feedback!