MGO/GOLANG:用于解组带有结构的文档。

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

MGO/GOLANG: Struct to unmarshall a document with

问题

我有一个类似这样的Mongo模式:

var phoneBookSchema = Schema({

    user_id: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        index: {
            unique : true
        },
        required: true
    },

    entries: {
        type: [entry],
        default: []
    },

    matches: {
        type: [],
        default: []
    }

});

entry文档的数组如下所示:

var entry = Schema({

    _id : false,

    phone: {
        type: String,
        index: true
    },

    name: {
        type: String
    },

    notified: {
        type: Boolean,
        default: false,
        required: true
    }

});

我应该如何在Golang中格式化PhoneBook结构体,以便可以运行以下查询并将结果解组为PhoneBook的数组?

var results []PhoneBook

err = pb.Find(bson.M{}).All(&results)
英文:

I have a Mongo schema that looks like this:

  var phoneBookSchema = Schema({

      user_id: {
          type: Schema.Types.ObjectId,
          ref: 'User',
          index: {
              unique : true
          },
          required: true
      },

      entries: {
          type: [entry],
          default: []
      },

      matches: {
          type: [],
          default: []
      }

  });

The array of entry documents looks like this:

  var entry = Schema({

        _id : false,

        phone: {
              type: String,
              index: true
        },

        name: {
              type: String
        },

        notified: {
              type: Boolean,
              default: false,
              required: true
        }

  });

How do I format the PhoneBook struct in Golang so that I can run a query like this and unmarshall the results into an array of PhoneBooks?

  var results []PhoneBook

  err = pb.Find(bson.M{}).All(&results)

答案1

得分: 2

我已经弄清楚了,以下是答案,希望对需要的人有用。

type PhoneBook struct {
    User_id bson.ObjectId
    Entries []Entry
    Matches []User
}

type Entry struct {
    Phone string
    Name string
    Notified bool
}

type User struct {
    User_id string
    Username string
}

我已经将代码翻译成中文了。

英文:

I figured it out, here is the answer for anyone who might find it useful.

type PhoneBook struct {
    User_id bson.ObjectId
    Entries []Entry
    Matches []User
}

type Entry struct {
    Phone string
    Name string
    Notified bool
}

type User struct {
    User_id string
    Username string
}

huangapple
  • 本文由 发表于 2014年5月1日 06:42:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/23399318.html
匿名

发表评论

匿名网友

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

确定