как создать пакет mon go db - PullRequest
0 голосов
/ 09 мая 2020

Я бы хотел построить инфраструктуру, которая представляет собой пакет для проекта. Чтобы другие разработчики могли импортировать этот пакет для выполнения операций CRUD с БД.

Но у меня во время теста возникла ошибка:

type Students struct {
    Name      string
    Age int
}

type InsertOneResult struct {
    InsertedID interface{}
}

func dbGetOne(coll, document interface{}) (*InsertOneResult, error) {
...
}

func dbUpdateOne(coll, document interface{}) (*InsertOneResult, error) {
    ...
}

func dbDeleteOne(coll, document interface{}) (*InsertOneResult, error) {
    ...
}

func dbInsertOne(coll, document interface{}) (*InsertOneResult, error) {
    res, err := coll.InsertOne(context.TODO(), document)
    if err != nil {
        log.Fatal(err)
    }
    return &InsertOneResult{InsertedID: res[0]}, err
}

func main() {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://<user>:<password>@<host>:<port>/<dbname>"))
    if err != nil {
        log.Fatal(err)
    }

    ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }

    coll := client.Database("db").Collection("students")
    data := Students{"Amy", 10}
    res, err := dbInsertOne(coll, data)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("inserted document with ID %v\n", res.InsertedID)
}

Вот ошибка:

./main.go:24:18: coll.InsertOne undefined (type interface {} is interface with no methods)

Есть ли способ решить эту проблему? Заранее спасибо.

1 Ответ

1 голос
/ 09 мая 2020

Эй, похоже, ошибка может быть связана с преобразованием типа. Решением было бы четко определить тип для coll как *mongo.Collection в функции dbInsertOne(). Это позволяет компилятору во время компиляции определить структуру ввода вместо того, чтобы полагаться на абстрактный интерфейс.

func dbInsertOne(coll *mongo.Collection, document interface{}) (*InsertOneResult, error) {
    res, err := coll.InsertOne(context.TODO(), document)
    if err != nil {
        log.Fatal(err)
    }
    return &InsertOneResult{InsertedID: res.InsertedID}, err
}

Я бы также предложил, чтобы второй аргумент document также был типизированным известный термин, если возможно. например,

func dbInsertOne(coll *mongo.Collection, document Students)

Stati c набор текста немного поможет и устранит любую путаницу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...