【发布时间】:2016-02-27 15:29:56
【问题描述】:
我的任务是写历史聊天。因此,为了创建历史记录,我需要将每条消息发送到 Mongodb,当我有下一次连接时,我需要获取所有消息,并通过循环发送给所有连接到聊天的客户端
这是我的聊天服务器的代码
func ChatServer(ws *websocket.Conn) {
// Connecting to MongoDB, collection History
session, err := mgo.Dial("mongodb://******:*******@ds045795.mongolab.com:45795/catalog")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("catalog").C("History")
// fmt.Println(c.Find())
// Adding clients to the map
clientId := ws.RemoteAddr().String()
defer ws.Close()
clients[ws] = true
// Loop for receiving msg
for {
var msg string
// If can not read msg - delete client from map
if err := websocket.Message.Receive(ws, &msg); err != nil {
delete(clients, ws)
return
}
sendAll(msg)
err = c.Insert(&Connect{clientId, msg})
if err != nil {
log.Fatal(err)
}
}
}
所以我的问题是按顺序从集合中获取所有元素。 我不知道该怎么做,因为在文档中找不到合适的功能。 也许您还有其他优惠?
【问题讨论】:
-
您没有在消息中插入时间戳?
-
不,我没有插入时间戳
-
那么“顺序”是如何确定的呢?自动?
-
集合中的索引,但我不知道如何检测集合的长度和文档的索引