dongrenzheng1619 2017-08-17 15:22
浏览 54
已采纳

MGO返回bson字段而不是json字段

The bson name is used when performing pipe in mgo. Struct :

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"`
}

Function :

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 result :

{
  "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": ""
          },
        }
      ]
    }
  ]
}

As you can see field _id is generated instead of id. That's not happen if I use find or findId. Is there any way to keep using json field no matter what's the query?

  • 写回答

1条回答 默认 最新

  • dpjw67160 2017-08-17 16:20
    关注

    The way you're reading the result, it has no idea what the JSON field names are. In order for it to use those tags, it must actually deserialize into the struct where the tags have been specified. When you do:

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

    You're explicitly telling mgo to return BSON results. The object you pass in (a slice of bson.M) has no json tags on it. In order to control the serialization to JSON, you must pass a struct with the JSON tags specified to All:

        resp := []Training
        db.C(common.C_TRAINING).Pipe(pipeline).All(&resp)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格