MongoDB保存带有空的ObjectId引用的文档时出错:错误:JSON中的无效ObjectId。

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

Mongo save document with empty objectid reference - error: Invalid ObjectId in JSON

问题

我正在使用golang服务器,并连接到Mongo数据库。

我有以下的参考结构:

type A struct {
	Id   bson.ObjectId    `bson:"_id" json:"id"`
	B    bson.ObjectId    `bson:"b,omitempty" json:"b,omitempty"`
}

问题是,在A中,B字段是可选的,但是当我尝试保存没有B字段的A时,我会收到一个错误信息:

"Invalid ObjectId in JSON: null"

我该如何使这个引用字段变为非必需的?

英文:

I'm working on golang server, connected to mongo.

I have a the following reference structure:

type A struct {
	Id   bson.ObjectId    `bson:"_id" json:"id"`
	B    bson.ObjectId    `bson:"b,omitempty" json:"b,omitempty"`
}

Thing is, B is not mandatory in A, and when ever I try to save A without B i'm getting an error:

"Invalid ObjectId in JSON: null"

How can I have this reference be no mandatory?

答案1

得分: 1

你可以尝试使用以下代码:

type A struct {
    Id bson.ObjectId  `bson:"_id" json:"id"`
    B  *bson.ObjectId `bson:"b,omitempty" json:"b,omitempty"`
}
英文:

Can you try with:

type A struct {
    Id bson.ObjectId  `bson:"_id" json:"id"`
    B  *bson.ObjectId `bson:"b,omitempty" json:"b,omitempty"`
}

huangapple
  • 本文由 发表于 2015年10月29日 18:51:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/33412211.html
匿名

发表评论

匿名网友

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

确定