当前位置: > > > > 无法从 MongoDB 读取类型为“strfmt.DateTime”的 time_stamp
无法从 MongoDB 读取类型为“strfmt.DateTime”的 time_stamp
来源:stackoverflow
2024-04-23 20:36:36
0浏览
收藏
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天米云就整理分享《无法从 MongoDB 读取类型为“strfmt.DateTime”的 time_stamp》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我正在尝试将 strfmt.datetime 类型(https://godoc.org/github.com/go-openapi/strfmt#datetime)的时间戳写入 mongodb
我可以成功地将这种格式的日期写入数据库,如下所示:
{ “_id”:objectid(“5bcb58f7540ac6d0bc946e22”),“状态”:“测试”,“时间戳”:{ “数据”:“2018-10-21t00:33:59.699+08:00” } }
但是我无法从mongodb中检索它,time_stamp的值总是显示0001-01-01t00:00:00.000z,我只是不明白为什么。
这是我的代码,欢迎任何建议或意见!谢谢
package main
import (
"fmt"
"time"
"github.com/go-openapi/strfmt"
"github.com/op/go-logging"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type TxStatus struct {
Status string `json:"status" bson:"status"`
TimeStamp *strfmt.DateTime `json:"time_stamp" bson:"time_stamp"`
}
type MongoDBOperations struct {
mongoSession *mgo.Session
database string
collection string
}
var log = logging.MustGetLogger("example")
func main() {
mo := MongoDBOperations{}
mo.database = Database
mo.collection = Collection
// We need this object to establish a session to our MongoDB.
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
Username: AuthUserName,
Password: AuthPassword,
}
// Create a session which maintains a pool of socket connections
// to our MongoDB.
var err error
mo.mongoSession, err = mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
mo.mongoSession.SetMode(mgo.Eventual, true)
write(mo)
read(mo)
}
func write(mo MongoDBOperations) {
log.Info("write operation")
session := mo.mongoSession.Copy()
defer session.Close()
c := session.DB(Database).C(Collection)
timestamp := strfmt.DateTime(time.Now())
txStatus := TxStatus{
Status: "test",
TimeStamp: ×tamp,
}
if err2 := c.Insert(txStatus); err2 != nil {
panic(err2)
}
}
func read(mo MongoDBOperations) {
log.Info("write operation")
session := mo.mongoSession.Copy()
defer session.Close()
c := session.DB(Database).C(Collection)
// Find and Count
var status []TxStatus
err2 := c.Find(bson.M{"status": "test"}).All(&status)
if err2 != nil {
panic(err2)
}
for _, elem := range status {
fmt.Printf("%+v\n", elem)
}
}
解决方案
我仔细研究了 github.com/go-openapi/strfmt 的代码,发现他们使用的是 github.com/globalsign/mgo 而不是 gopkg.in/mgo.v2。将导入更改为使用 github.com/globalsign/mgo 和 github.com/globalsign/mgo/bson 已修复该问题。 Globalsign 包是 mgo.v2 的分支,因此方法保持不变,除了导入之外不需要更改任何代码。
终于介绍完啦!小伙伴们,这篇关于《无法从 MongoDB 读取类型为“strfmt.DateTime”的 time_stamp》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~米云公众号也会发布Golang相关知识,快来关注吧!
