2017-08-17 113 views
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字段?

回答

1

您讀取結果的方式,它不知道JSON字段名稱是什麼。爲了使用這些標籤,它必須實際反序列化到標籤已被指定的結構中。當您這樣做時:

resp := []bson.M{} 
    db.C(common.C_TRAINING).Pipe(pipeline).All(&resp) 

您明確告訴mgo返回BSON結果。您傳入的對象(bson.M的片段)上沒有json標記。爲了控制序列化到JSON,你必須通過一個結構與指定All的JSON標籤:

resp := []Training 
    db.C(common.C_TRAINING).Pipe(pipeline).All(&resp) 
+0

但是,這將去掉'lookup'數據,不是嗎? 如果我們需要爲每個自定義連接('lookup')創建結構體,我認爲在這個過程中會有點問題。或者,有沒有處理這種東西的最佳做法? –

+0

如果您需要控制JSON字段名稱,並且它們與BSON字段名稱不匹配,則必須提供映射。這些映射最容易在結構標籤中提供。這意味着您必須將結果反序列化爲與結果結構匹配的結構。你可以使用匿名結構,但並不能節省很多,代碼量大致相同。 – Adrian

+0

好的,謝謝阿德里安的回答。 –