首页 > 解决方案 > 如何在mgo Golang中的_id以外的字段中保存空objectId

问题描述

我正在尝试使用结构在数据库中保存一个字段。在这种情况下,如果我初始化这个结构并且在执行更新操作时没有将有效的 bson id 作为 MasterTemplateId 传递,那么它会给出错误。

对于我的要求,我需要id整数和master_template_idbson id,因为它在这里用作参考 id。

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)
}

执行此操作后,更改notificationTemplate.MasterTemplateId = bson.NewObjectId()notificationTemplate.MasterTemplateId = "".

它给出以下错误:

ObjectIDs must be exactly 12 bytes long (got 0)

如何在数据库中保存空的 bson id?

MasterTemplateId注意:由于项目结构,我不能将指针用于字段。

标签: mongodbgomgo

解决方案


推荐阅读