If you want to play with MongoDB Change Streams on your local machine, you will have to convert your mongo instance to a replica set.

There is a tutorial on mongodb.com on how to do that, but I found that I needed some help on getting it working.

Oh, and you will need at least MongoDB 3.6 for Change Streams, so if you have an older version, you have to upgrade it first…

Anywho, here is everything I had to do to make it work on my Windows machine.

First, I stopped my mongo service.

Then I looked into my mongod.cfg file and saw that it looked something like this:

systemLog:
    destination: file
    path: C:/mongodb/log/mongod.log
storage:
    dbPath: C:/mongodb/data

This turned out to be a problem, because we need to start the mongodb server with the replSet parameter set.

Long story short, I ended up converting that mongod.cfg file to this:

# data directory
dbpath=C:/mongodb/data

# log file
logpath=C:/mongodb/log/mongod.log
logappend=true

# replica set name
replSet=rs

Then I started the server, opened the mongo console, and executed:

rs.initiate()

Then I executed:

db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )

And checked that the change is good by executing:

db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )

Then I restarted the server once more, just to be safe.

I then I added these few lines into my nodejs code, where I already had mongoose running with the User model:

const userChangeStream = User.watch([],	{fullDocument: "updateLookup"});
userChangeStream.on('change', (change) => {
	console.log(' - user change stream event:\n', change);
});

And I opened Robo 3T, changed the updatedAt field for a user, et voilà:

{
  "operationType": "update",
  "updateDescription": {
    "updatedFields": {
      "updatedAt": "2020-07-04T15:49:34.498Z"
    },
    "removedFields": []
  }
}

Change Streams are comming in 🙂

Categories: Programming

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.