Mongodb notify on document updated
Say this is a document schema
'use strict';import mongoose from 'mongoose';var MessageSchema = new mongoose.Schema({ toid: String, fromid: String, toname: String, fromname: String, content: String, date: { type: Date, default: Date.now }});export default mongoose.model('Message', MessageSchema);
And here is the backend code where where you change the contents of document
import {Router} from 'express';var router = new Router();router.post('/create/:id', function(req, res){return Message.create(req.body) .then(respondWithResultAndEmitAnEvent(res, 201)) .catch(handleError(res));});
So this respondWithResultAndEmitAnEvent function look something like this,as the name suggest where even a user POST a data to server (say on the url xyz.com/api/create/:id ) the server will emit an event that can be captured by other clients.
function respondWithResultAndEmitAnEvent(res, statusCode) { statusCode = statusCode || 200; return function(entity) { if (entity) { socket.emit('message_added', entity); res.status(statusCode).json(entity); } };}
On the client side you can listen to this event "message_added" and update it.
socket.on('message_added', function ( data ) { console.log(data); //update the client with new data; });
If you have control of the other process, than I would recommend doing it proactively, meaning that the process of saving is what triggers the code that is "watching" for changes. Otherwise, you could do interval polling, but that is usually inefficient, and generally bad design. You could also look into some of the more interesting methods, such as watching the Mongo Oplog.