Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb notify on document updated

Imagine if i had a mongodb with some documents and a nodejs server which emits json data from the mongodb to the client using socket.io, and some process has updated that mongodb document that is currently in the client view, i was wondering if there is a way so that the mongodb notifies the nodejs server when the object gets updated by anyone other than the client himself so that i could emit the updated document json through the open socket, is such thing possible?

i have tried to find some resources on google with no luck.

like image 703
Kanka Avatar asked Jan 16 '14 18:01

Kanka


People also ask

How can I tell when a document was last updated in MongoDB?

To get last inserted document, use sort() along with limit(1).

Does MongoDB update automatically?

No, there is no such thing (autoupdate) in MongoDB. It must be done with application or script.

Does MongoDB support triggers?

Database Triggers use MongoDB change streams to listen for changes to documents in a collection and pass database events to their associated Trigger function. You can use a $match expression document to filter change events based on field values.


Video Answer


1 Answers

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;
    }); 
like image 86
Harsh Gupta Avatar answered Sep 18 '22 21:09

Harsh Gupta