mongodb - 如何在mgo Golang中的_id以外的字段中保存空objectId
问题描述
我正在尝试使用结构在数据库中保存一个字段。在这种情况下,如果我初始化这个结构并且在执行更新操作时没有将有效的 bson id 作为 MasterTemplateId 传递,那么它会给出错误。
对于我的要求,我需要id
整数和master_template_id
bson 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
注意:由于项目结构,我不能将指针用于字段。
解决方案
推荐阅读
- zk - 如何在 ZK 日历中禁用过去的日子?
- python - 如何计算 pytorch 中关键点检测 CNN 模型的准确度?
- python - Django,如何从 DateField 中每月提取值列表?
- java - nginx.conf 中的“location /logs”和“location /logs/”有什么区别
- javascript - 如何在具有背景颜色的同时一一粘贴标题?
- scala - Scala 以列表为键、字符串为值的地图展平
- ios - HTML
- python - 描述中提到的具有所有子图的大图
- java - 我正在制作一个简单的 JavaFx 程序。只需一个按钮即可查看错误
- vb.net - 有人如何从数据库表中选择 datat 到树视图控件 VB.NET?