Search code examples
mongodbmongoose

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 ?


Solution

  • 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