英文:
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:"-"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论