英文:
How to update array inside Go model for Mongo
问题
我有一个Go语言中的Player模型和Level模型。
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"`
}
如果我有PlayerModel的实例(player指针),如何更新其中的Level?Player可以玩新的(尚未玩过的)关卡(然后插入),或者已经玩过(如果时间低于已达到的关卡时间,则更新)。
英文:
I have Player model in Go for Mongo and model Level
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 instance of PlayerModel ( player pointer ) ?
Player can play new ( not yet played ) level ( then insert ) or already played ( just update if time is lower then already achieved for that level ).
答案1
得分: 3
如果只是更新内存中的数据结构(无论它是否映射到MongoDB文档),可以应用一个简单的算法,例如:
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})
}
在此处查看示例:https://play.golang.org/p/C8SGqkgZ99
英文:
If this is just about updating a data structure in memory (whether it maps a MongoDB document or not), a naive algorithm can be applied, such as:
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 at: https://play.golang.org/p/C8SGqkgZ99
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论