Example pub/sub using mongodb
This example uses tailable
cursor to wait data that inserted to mongodb. Tailibale cursor is like tail -f
command in Unix.
To use this example collection should be capped
(only capped
collections support Tailable Cursor). Capped collection is fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size. To create it in mongo
client:
run db.createCollection('messages', { capped: true, size: 100000 });
var mongo = require("mongodb"), // mongodb client
io = require("socket.io"), // socket io server
http = require("http");
var app = http.createServer((req, res) => {
res.writeHead(200);
res.end("Socket.io example");
});
io = io.listen(app);
app.listen(3000);
console.log("http server on port 3000");
mongo.MongoClient.connect ('mongodb://127.0.0.1/test_db', (err, db) => {
// db initialized
db.collection('messages', function(err, collection) {
// Grab the messages collection
io.sockets.on("connection", function (socket) {
// when client connects
// open a tailable cursor, and find all documents
collection.find({}, {
tailable:true, // the cursor is tailable
awaitdata:true, // allow the cursor to wait for data
numberOfRetries:-1 // the number of times to retry on timeout.
}).sort({ $natural: 1 }).each((err, doc) => {
// send message to client
if (doc.type == "message") {
socket.emit("message",doc);
}
})
});
});
});