MarAja
MarAja

Reputation: 1597

Basic trigger on MongoDB insert

I am trying to have a triggering on an insert in my collection (mycollection) on my Mongo database (mydatabase). Here is the javascript code ready to trigger on insert.

var MongoClient = require('mongodb').MongoClient;
var triggers = require("mongo-triggers");

MongoClient.connect('mongodb://localhost:27017/mydatabase', function(err, db) {
  var myCollection = db.collection('mycollection');
  triggers(myCollection).insert(function(document, next) {
    console.log("Triggered on insert");
    next();
  });
});

When I use the mongo CLI to make an insert:

> use mydatabase
> db.mycollection.insert({"test": 1})

Nothing is triggered (no print on stdout). Any ideas?

Upvotes: 0

Views: 2143

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

The trigger you're defining using the mongo-triggers library only works within the context of the node.js program where you define the trigger.

So you'd only get the output if you inserted a document in the same program that your code sample is from.

MongoDB doesn't have any built-in support for triggers, so this is only a client-side trigger.

Upvotes: 1

Related Questions