没有使用MongoDB和Golang时的解码器错误

huangapple go评论80阅读模式
英文:

No decoder error using MongoDB and Golang

问题

我有一个存储在MongoDB中的结构体。

type Step struct {
	Name           string
	CompensateFunc interface{}
	Error          error       `bson:"error,omitempty"`
	Result         interface{} 
}

这个结构体可以成功地存储在Mongo中,但是当我尝试获取它时,出现以下错误:

error decoding key steps.0.error: no decoder found for error

我需要在MongoDB中存储Golang错误时需要做些什么吗?

英文:

I have a struct that I am storing within MongoDB

type Step struct {
	Name           string
	CompensateFunc interface{}
	Error          error       `bson:"error,omitempty"`
	Result         interface{} 
}

The struct gets stored in Mongo fine but when I try and fetch it I get the following error:

error decoding key steps.0.error: no decoder found for error

Is there something I need to do to store Golang errors within a MongoDB?

答案1

得分: 2

原来是因为Mongo无法直接解码接口,它只能解码简单类型。

为了修复这个错误,我将底层错误字符串存储在结构体上

type Step struct {
	Error  string 
}
英文:

It turns out this is because Mongo can't decode interfaces out of the box, it can only decode simple types.

To fix the error I stored the underlying error string on the struct instead

type Step struct {
	Error  string 
}

huangapple
  • 本文由 发表于 2023年4月6日 21:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定