3

I was creating unary tests when I got stuck on the following situation:

  • I have an object that has a foreign key. For some reason, I need to switch the ID and it works. However, sometimes, I need to remove this ID. If I have an ID, I realise a certain action and if I don't, then nothing happens.

However, I can't find the way to set my bson.ObjectId as nil or zero.

Does anyone knows how to do or a work around?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Emixam23
  • 3,854
  • 8
  • 50
  • 107
  • 2
    This is like &string("Hello"). It's invalid. But you can store the `bson.ObjectIdHex(id)` value to some `tmp` variable and then assign `&tmp` it to the `*bson.ObjectID` variable. – dom Dec 16 '18 at 01:27
  • Maybe there is a better way to implement it, but I would have to see the code snippet. – dom Dec 16 '18 at 01:32

3 Answers3

10

Or you can use the primitive.NilObjectID

NilObjectID is the zero value for ObjectID.

Bastien
  • 994
  • 11
  • 25
2

bson.ObjectId is an alias for string , therefore the zero value is an empty string ""

Mostafa Solati
  • 1,235
  • 2
  • 13
  • 33
2

Based on @dom answer (in the comments), there is the workaround I am now using:

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
}

Also, as said @dom, I am now saving my mongoDB ID as *bson.ObjectId instead of bson.ObjectId. Example:

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"`
}

I hope it helps !

Emixam23
  • 3,854
  • 8
  • 50
  • 107