1

I'm receiving this error when trying to convert interface{} to struct type in golang.

interface conversion: interface {} is primitive.D, not model.ClientModel. Error in line : cm := res.(model.ClientModel)

res, err := db.FindOne(collection, filter)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(res)

    cm := res.(model.ClientModel)
    fmt.Println(cm)
2
  • 2
    The error is pretty clear. What's the question? Commented Jun 6, 2019 at 8:12
  • What driver are you using ? FindOne returns a *SingleResult in mongo-driver v1.5+. You can keep it generic until a call to Decode. Commented Apr 23, 2021 at 15:55

1 Answer 1

1

You can .Decode(&foo) the SingleResult returned from FindOne().

var cm model.ClientModel
err := db.FindOne(collection, filter).Decode(&cm)
if err != nil {
    fmt.Println(err)
}
fmt.Println(cm)

See https://godoc.org/go.mongodb.org/mongo-driver/mongo#SingleResult for details.

Sign up to request clarification or add additional context in comments.

1 Comment

I cannot pass model to decode function as I'm trying to make it work with generic type by passing interface. The result of decode is stored in interface which eventually i want to return outside function and convert to struct in service layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.