3 回答
TA贡献1906条经验 获得超3个赞
我现在使用的是解决方法:
package your_package
import "github.com/globalsign/mgo/bson"
func GenerateNewGuidHelper() *bson.ObjectId {
id := bson.NewObjectId()
return &id
}
func IsStringIdValid(id string) bool {
return id != "" && bson.IsObjectIdHex(id)
}
func ConvertStringIdToObjectId(id string) *bson.ObjectId {
if id != "" && bson.IsObjectIdHex(id){
bsonObjectId := bson.ObjectIdHex(id)
return &bsonObjectId
}
return nil
}
func ConvertStringIdsToObjectIds(ids []string) []*bson.ObjectId {
var _ids []*bson.ObjectId
for _, id := range ids {
_ids = append(_ids, ConvertStringIdToObjectId(id))
}
return _ids
}
func IsObjectIdValid(id *bson.ObjectId) bool {
return id.Hex() != "" && bson.IsObjectIdHex(id.Hex())
}
func ConvertObjectIdToStringId(id *bson.ObjectId) string {
if id != nil {
return id.Hex()
}
return ""
}
func ConvertObjectIdsToStringIds(ids []*bson.ObjectId) []string {
var _ids []string
for _, id := range ids {
_ids = append(_ids, ConvertObjectIdToStringId(id))
}
return _ids
}
我现在将我的 mongoDB ID 保存为而*bson.ObjectId不是bson.ObjectId. 例子:
package datamodels
import (
"github.com/globalsign/mgo/bson"
)
type User struct {
ID *bson.ObjectId `protobuf:"bytes,1,opt,name=id,proto3" json:"_id,omitempty" bson:"_id,omitempty"`
}
我希望它有所帮助!
- 3 回答
- 0 关注
- 153 浏览
添加回答
举报