How to update an array inside Go model for Mongo

I have a player model in Go for Mongo and a Level model

type LevelModel struct {
    Index           int                 `json: "index" bson: "index"`
    Time            int64               `json: "time" bson: "time"`
}


type PlayerModel struct {
    ID              bson.ObjectId       `json: "_id, omitempty" bson: "_id, omitempty"`
    Score           int64               `json: "score" bson: "score"`
    Level           []LevelModel    `json: "level" bson: "level"`
}

How to update Level from PlayerModel if I have a PlayerModel instance (player pointer)? The player can play a new (not yet played) level (then insert) or have already played (just update if the time is less than already reached for this level).

+4
source share
1 answer

If this is just an update of the data structure in memory (regardless of whether it displays a MongoDB document or not), you can use a naive algorithm, for example:

func (p *PlayerModel) updateLevel(idx int, time int64) {
    for i := range p.Level {
        lm := &(p.Level[i])
        if lm.Index == idx {
            if time < lm.Time {
                lm.Time = time
            }
            return
        }
    }
    p.Level = append(p.Level, LevelModel{idx, time})
}

See an example: https://play.golang.org/p/C8SGqkgZ99

+3
source

Source: https://habr.com/ru/post/1613963/


All Articles