0
在mgo中執行管道時使用bson名稱。 結構:MGO返回bson字段而不是json字段
type Training struct {
Id bson.ObjectId `json:"id" bson:"_id"`
Name string `json:"name" bson:"name"`
Description string `json:"description"`
Level *TrainingLevel `json:"level"`
Preworks []bson.ObjectId `json:"preworks"`
PrePostTests []bson.ObjectId `json:"preposttests" bson:"preposttests"`
TrainingEvaluations []bson.ObjectId `json:"training_evaluations" bson:"training_evaluations"`
TrainerEvaluations []bson.ObjectId `json:"trainer_evaluations" bson:"trainer_evaluations"`
AppCompanyId bson.ObjectId `json:"app_company_id" bson:"app_company_id"`
Company *Company `json:"company"`
}
功能:
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字段?
但是,這將去掉'lookup'數據,不是嗎? 如果我們需要爲每個自定義連接('lookup')創建結構體,我認爲在這個過程中會有點問題。或者,有沒有處理這種東西的最佳做法? –
如果您需要控制JSON字段名稱,並且它們與BSON字段名稱不匹配,則必須提供映射。這些映射最容易在結構標籤中提供。這意味着您必須將結果反序列化爲與結果結構匹配的結構。你可以使用匿名結構,但並不能節省很多,代碼量大致相同。 – Adrian
好的,謝謝阿德里安的回答。 –