无法从MongoDB读取'strfmt.DateTime'类型的时间戳
我正在尝试使用无法从MongoDB读取'strfmt.DateTime'类型的时间戳,mongodb,go,timestamp,Mongodb,Go,Timestamp,我正在尝试使用strfmt.DateTimetype()将时间戳写入mongodb 我可以成功地将此格式的日期写入数据库,如下所示: {“_id”:ObjectId(“5BC58F7540AC6D0BC946E22”),“状态”:“测试”,“时间戳”:{ “数据”:“2018-10-21T00:33:59.699+08:00”} 但是我无法从mongodb中检索它,时间戳的值总是显示0001-01-01T00:00:00.000Z,我不明白为什么 这是我的代码,欢迎任何建议或意见!谢谢 pack
strfmt.DateTime
type()将时间戳写入mongodb
我可以成功地将此格式的日期写入数据库,如下所示:
{“_id”:ObjectId(“5BC58F7540AC6D0BC946E22”),“状态”:“测试”,“时间戳”:{
“数据”:“2018-10-21T00:33:59.699+08:00”}
但是我无法从mongodb中检索它,时间戳的值总是显示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的分支,因此方法保持不变,除了导入之外,不需要更改任何代码。我深入研究了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驱动程序,而不是更改导入:(最新版本的库也有同样的问题,但现在他们使用的是官方的Mongodb驱动程序,这并不像更改导入那样简单:(