在文档中创建用户定义的键

I'm attempting to create a document with a user-defined key as follows:

package main

import (
    "fmt"
    driver "github.com/arangodb/go-driver"
    "github.com/arangodb/go-driver/http"
)

type doc struct {
    _key string `json:"_key"`
}

func main() {
    conn, _ := http.NewConnection(http.ConnectionConfig{
        Endpoints: []string{"http://localhost:8529"},
    })

    c, _ := driver.NewClient(driver.ClientConfig{
        Connection: conn,
        Authentication: driver.BasicAuthentication("root", "test"),
    })

    db, _ := c.CreateDatabase(nil, "dbname", nil)

    // delete the collection if it exists; then create it
    options := &driver.CreateCollectionOptions{
        KeyOptions: &driver.CollectionKeyOptions{
            AllowUserKeys: true,
        },
    }
    coll, _ := db.CreateCollection(nil, "collname", options)

    meta, _ := coll.CreateDocument(nil, doc{ _key: "mykey" })

    fmt.Printf("Created document with key '%s' in collection '%s'
", meta.Key, coll.Name())
}

I get the following output:

Created document with key '5439648' in collection 'collname'

I've tried with the property of the doc type as '_key', 'key' and 'Key'. None have worked.

The field needs to be visible (so uppercase) in order to be included in the JSON marshalling.

At the same time, the DB expects the JSON document to contain a _key attribute.

So you should specify it as:

type doc struct {
    Key string `json:"_key"`
}

Alternatively, you can try sending a map to the method:

coll.CreateDocument(nil, map[string]string{"_key": "mykey"})