【问题标题】:update an array element of a struct by mgo v2 (golang,mongoDB)通过 mgo v2 (golang,mongoDB) 更新结构的数组元素
【发布时间】:2019-06-07 17:12:13
【问题描述】:

我有这样的结构:

type Meet struct {
    Title   string    `json:title`
    Time    time.Time `json:time`
    Host    string    `json:host`
    Crowd   []string  `json:crowd`
    Geo     Location  `json:location`
    Invoice []Bill    `json:invoice`
}

type User struct {
    ID         bson.ObjectId   `json:"id" bson:"_id,omitempty"`
    Name       string          `json:name`
    Phone      string          `json:phone`
    Email      string          `json:email`
    Vc         string          `json:vc`
    Status     int8            `json:status`
    Avatar     string          `json:avatar`
    FriendList []bson.ObjectId `json:friendlist`
    Meetings   []Meet          `json:meetings`
    Requests   []Request       `json:request`
}

并且想要更新会议发票(例如:User.Meetings[0].Invoice) 我的代码是这样的:

        query := bson.M{
            "_id":            bson.ObjectIdHex(personId),
            "Meetings.Title": Title,
            "Meetings.Geo":   Geo,
        }
        update := bson.M{
            "$set": bson.M{
                "Meetings.$.Invoice": updateInvoice,
            },
        }

        updateErr = collection.Update(query, update)

我得到的只是没有找到错误。评论会议。地理没有帮助并导致同样的原因。没有找到。 这是我的查询有问题还是什么?

【问题讨论】:

    标签: mongodb go struct mgo


    【解决方案1】:

    查询中的字段应为 meeting.title 和 meeting.geo。我刚刚用我的一个数据库对其进行了测试,并且字段的情况很重要。在您的更新中,会议应该是会议。名称取自结构项目标签名称,而不是结构项目名称。例如

    struct test {
        ID bson.   bson.ObjectId `bson:"_id"`
        TestString string        `bson:"ts"`
        Amount     int           `bson:"am"`
    }
    
    query := bson.M{"ts": "test", "am": 2}
    

    您不能对 _id 进行 omitempty,因为 _id 字段必须存在。

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2013-09-07
      • 2017-07-02
      • 1970-01-01
      相关资源
      最近更新 更多