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.
To get last inserted document, use sort() along with limit(1).
No, there is no such thing (autoupdate) in MongoDB. It must be done with application or script.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With