Import mongodb and mongohook
const MongoHook = require('@dfrankes/mongohook');
// Pass in the mongodb package require, this will return a hooked mongodb package
const mongodb = new MongoHook(require('mongodb'), {});
You can now use the mongodb package as usual
mongodb.MongoClient.connect
Create a before hgook for the collection mycollection
// Create a before hook for the collection insertOne
// args is the original function arguments
// for a updateOne it uses the following layout
// args['0'] = the find query
// args['1'] = the update query ($set:{hello: true});
// just console.log the args to check what you can modify
// You can find a full example in example/index.js
client.collection('mycollection').before('insertOne', (args) => {
// args is an array with all the original method arguments
// You can for example modify a insertOne query like this
args['0'].createdAt = new Date();
// return the original arguments
// this will be executed in the original method
return args;
});
// Create a afterHook
client.collection('mycollection').after('insertOne', async (result) => {
console.log("after insertOne on mycollection");
});
hook |
---|
insert |
insertOne |
insertMany |
replaceOne |
update |
updateOne |
updateMany |