Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose how to listen for collection changes

I need to build a mongo updater process to dowload mongodb data to local IoT devices (configuration data, etc.)

My goal is to watch for some mongo collections in a fixed interval (1 minute, for example). If I have changed a collection (deletion, insertion or update) I will download the full collection to my device. The collections will have no more than a few hundred simple records, so it´s gonna not be a lot of data to download.

Is there any mechanism to find out a collection has changed since last pool ? What mongo features should be used in that case ?

like image 358
Mendes Avatar asked Jan 15 '18 19:01

Mendes


Video Answer


1 Answers

To listen for changes to your MongoDB collection, set up a Mongoose Model.watch.

const PersonModel = require('./models/person')

const personEventEmitter = PersonModel.watch()

personEventEmitter.on('change', change => console.log(JSON.stringify(change)))

const person = new PersonModel({name: 'Thabo'})
person.save()

// Triggers console log on change stream
// {_id: '...', operationType: 'insert', ...}

Note: This functionality is only available on a MongoDB Replicaset

See Mongoose Model Docs for more:

If you want to listen for changes to your DB, use Connection.watch.

See Mongoose Connection Docs for more

These functions listen for Change Events from MongoDB Change Streams as of v3.6

like image 80
Matt Avatar answered Sep 23 '22 08:09

Matt