MGO返回bson字段而不是json字段
在mgo中执行管道时使用bson名称。 结构: 功能:MGO返回bson字段而不是json字段,json,go,bson,mgo,revel,Json,Go,Bson,Mgo,Revel,在mgo中执行管道时使用bson名称。 结构: 功能: func (this *TrainingClass) GetAllTraining() (interface{}, error) { if !this.tokenInfo.IsAllowed(this.c) { return nil, tlib.NewTError(common.Error_NoAccess, "You don't have the right!") } sess, db := Get
func (this *TrainingClass) GetAllTraining() (interface{}, error) {
if !this.tokenInfo.IsAllowed(this.c) {
return nil, tlib.NewTError(common.Error_NoAccess, "You don't have the right!")
}
sess, db := GetDB()
defer sess.Close()
pipeline := []bson.M{
{"$match": bson.M{
"app_company_id": this.tokenInfo.AppCompanyId}},
{"$lookup": bson.M{
"from": "trainingbatch",
"localField": "_id",
"foreignField": "training._id",
"as": "trainingbatches"}},
}
resp := []bson.M{}
db.C(common.C_TRAINING).Pipe(pipeline).All(&resp)
return bson.M{"data": resp}, nil
}
Json结果:
{
"data": [
{
"_id": "5995a749dbcfbe4e8cc31378",
"app_company_id": "58b24756e65bd121f6b1a923",
"description": "Description First Training",
"name": "First Training",
"trainingbatches": [
{
"_id": "5995a74adbcfbe4e8cc31379",
"app_company_id": "58b24756e65bd121f6b1a923",
"company": {
"_id": "58b24756e65bd121f6b1a923",
"address": "",
"app_company_id": "58b24756e65bd121f6b1a923",
"fullname": "",
"name": "Tandem",
"phone": ""
},
}
]
}
]
}
正如您所看到的,字段_id是生成的,而不是id。如果使用find或findId,则不会发生这种情况。无论查询是什么,有没有办法继续使用json字段?您读取结果的方式,它不知道json字段名是什么。为了使用这些标记,它必须实际反序列化到指定标记的结构中。当您这样做时:
resp := []bson.M{}
db.C(common.C_TRAINING).Pipe(pipeline).All(&resp)
您明确告诉mgo返回BSON结果。您传入的对象(一片bson.M
)上没有json标记。为了控制对JSON的序列化,必须传递一个带有JSON标记的结构,该标记指定为All
:
resp := []Training
db.C(common.C_TRAINING).Pipe(pipeline).All(&resp)
从读取结果的方式来看,它不知道JSON字段名是什么。为了使用这些标记,它必须实际反序列化到指定标记的结构中。当您这样做时:
resp := []bson.M{}
db.C(common.C_TRAINING).Pipe(pipeline).All(&resp)
您明确告诉mgo返回BSON结果。您传入的对象(一片bson.M
)上没有json标记。为了控制对JSON的序列化,必须传递一个带有JSON标记的结构,该标记指定为All
:
resp := []Training
db.C(common.C_TRAINING).Pipe(pipeline).All(&resp)
但是,这将剥离
查找数据,不是吗?如果我们需要为每个自定义联接(lookup
)创建struct,我认为在这个过程中会有点问题。或者,在处理这类内容方面有什么最佳实践吗?如果需要控制JSON字段名,而它们与BSON字段名不匹配,则必须提供映射。这些映射最容易在struct标记中提供。这意味着您必须将结果反序列化为与结果结构匹配的结构。您可以使用匿名结构,但它不会为您节省太多,代码量大致相同。但是,这将剥离查找
数据,不是吗?如果我们需要为每个自定义联接(lookup
)创建struct,我认为在这个过程中会有点问题。或者,在处理这类内容方面有什么最佳实践吗?如果需要控制JSON字段名,而它们与BSON字段名不匹配,则必须提供映射。这些映射最容易在struct标记中提供。这意味着您必须将结果反序列化为与结果结构匹配的结构。您可以使用匿名结构,但它不会为您节省很多,代码量大致相同。