英文:
Creating user-defined keys in document
问题
我正在尝试创建一个具有用户定义键的文档,代码如下:
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'\n", meta.Key, coll.Name())
}
我得到以下输出:
Created document with key '5439648' in collection 'collname'
我尝试过将doc类型的属性命名为_key、key和Key,但都没有成功。
英文:
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'\n", 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.
答案1
得分: 6
字段需要可见(大写)才能包含在JSON编组中。
同时,数据库期望JSON文档包含一个_key属性。
所以你应该这样指定:
type doc struct {
    Key string `json:"_key"`
}
或者,你可以尝试将一个map发送给该方法:
coll.CreateDocument(nil, map[string]string{"_key": "mykey"})
英文:
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"})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论