如何在Go语言中向空切片中添加元素?

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

How to $push to a null slice in golang

问题

在从mgo迁移到go-mongo驱动程序后,[]model被更新为null而不是空数组,所以我无法对golang结构执行$push操作。即使数组为空,也有办法进行$push吗?

type Sample struct {
	Data string   `json:"data,omitempty" valid:"-"`
	Exam []Result `json:"exam" valid:"-"`
}

type Result struct {
	Field1 string `json:"field1,omitempty"`
	Field2 string `json:"field2,omitempty"`
}

// 我尝试的操作
var result m.Result
err := db.sampleCollection.UpdateOne(bson.M{"id": sampleID}, bson.M{"$push": bson.M{"exam": result}})

但是在插入期间,字段result被设置为null而不是空的[]array,所以它不允许进行$push操作。因为它不是一个数组,只是一个对象,在旧的mgo驱动程序中,它可以正常工作,因为它从未被设置为null。

英文:

After the code migration from mgo to go-mongo driver the []model are getting updated with null instead of empty array , So i'm not able to do $push operation for a golang struct . How to $push even if the array is null is there a way ?


type Sample struct {
	Data     string                   `json:"data,omitempty" valid:"-"`
	Exam     []Result                 `json:"exam" valid:"-"`
}

type Result struct {

	field1          string `json:"field1,omitempty"`
	field2          string `json:"field2,omitempty"`

}

//what I try to do

var result m.Result  
err := db.sampleCollection.UpdateOne(bson.M{"id": sampleID}, bson.M{"$push": bson.M{"exam": result}})

But during insert the field result is set to null instead of empty []array , So it's not allowing to do a $push operation . Since that's not an array and just an object, In the old mgo driver it used to work fine because it was never set to null .

答案1

得分: 1

我认为你可以在bson标签中添加omitempty。当你插入一个文档时,如果该字段没有任何元素,Mongo将不会插入任何内容(我是指该文档中没有该名称的字段),所以当你想要更新它($push)时,Mongo将不会出现任何错误,并且你可以这样做。

type Sample struct {
    Data     string                   `bson:"data,omitempty" json:"data,omitempty" valid:"-"`
    Exam     []Result                 `bson:"exam,omitempty" json:"data,omitempty" valid:"-"`
}
英文:

I think you can add omitempty to the bson tag. When you're inserting a document and that field has not any element, mongo will not insert anything (I mean there was no field with that name in that document) so when you want to update it ($push), mongo will not find any error on it and you can do it.

type Sample struct {
    Data     string                   `bson:"data,omitempty" json:"data,omitempty" valid:"-"`
    Exam     []Result                 `bson:"exam,omitempty" json:"data,omitempty" valid:"-"`
}

huangapple
  • 本文由 发表于 2022年12月2日 18:54:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/74654601.html
匿名

发表评论

匿名网友

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

确定