How to save empty objectId in a field other than _id in mgo Golang

823 Views Asked by At

I am trying to save a field in the database using a struct. In this, if I initialize this struct and do no pass a valid bson id as MasterTemplateId while performing an update operation, then it gives error.

For my requirement I need id as integer and master_template_id as bson id because it is used as reference id here.

package main

import (
    "fmt"
    "time"

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type NotificationTemplate struct {
    Id               int           `json:"id,omitempty" bson:"_id,omitempty"`
    Name             string        `json:"name,omitempty" bson:"name,omitempty"`
    Slug             string        `json:"slug,omitempty" bson:"slug,omitempty"`
    Type             string        `json:"type,omitempty" bson:"type,omitempty"`
    MasterTemplateId bson.ObjectId `json:"master_template_id" bson:"master_template_id"`
}

func Update(collectionName string, id int, notificationTemplate NotificationTemplate) error {
    fetchedTemplate := NotificationTemplate{}
    mongoSession := ConnectDb("test1")
    defer mongoSession.Close()

    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()

    query := bson.M{"$set": notificationTemplate}
    getCollection := sessionCopy.DB("test1").C(collectionName)
    err := getCollection.Find(bson.M{"_id": id}).One(&fetchedTemplate)
    if err == nil {
        err2 := getCollection.Update(bson.M{"_id": id}, query)
        fmt.Println("err2", err2)
        return err2
    } else {
        err1 := getCollection.Insert(notificationTemplate)
        fmt.Println("err1", err1)
        return err1
    }
}

func ConnectDb(merchantDb string) (mongoSession *mgo.Session) {
    mongoDBDialInfo := &mgo.DialInfo{
        Addrs:    []string{"127.0.0.1:27017"},
        Database: merchantDb,
        Timeout:  60 * time.Second,
    }

    mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
    if err != nil {
        fmt.Printf("CreateSession: %s\n", err)
        defer mongoSession.Close()
        return mongoSession
    }
    mongoSession.SetMode(mgo.Monotonic, true)
    return mongoSession
}

func main() {
    notificationTemplate := NotificationTemplate{}
    notificationTemplate.Id = 1
    notificationTemplate.Name = "template1"
    notificationTemplate.MasterTemplateId = bson.NewObjectId()
    err := Update("test_collection", notificationTemplate.Id, notificationTemplate)
    fmt.Println(err)
}

after performing this, change notificationTemplate.MasterTemplateId = bson.NewObjectId() to notificationTemplate.MasterTemplateId = "".

it gives following error:

ObjectIDs must be exactly 12 bytes long (got 0)

How can I save empty bson id in the database??

Note: I can not use pointer for MasterTemplateId field due to project structure.

0

There are 0 best solutions below