Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable auditing and log all CRUD operations in MongoDB Node App?

I have a node mongo app. Now I want to show audit trail for some specific crud events which are happening in the application.

What would be the best approach for solving this problem ?

I have considered of creating a new collection and service which would be called in each method in node app for logging the operations.

like image 389
Ved Agarwal Avatar asked May 22 '16 17:05

Ved Agarwal


People also ask

How do I enable auditing in MongoDB?

Enable and Configure Audit Output The auditing facility can write audit events to the console, the syslog, a JSON file, or a BSON file. To enable auditing in MongoDB Enterprise, set an audit output destination with --auditDestination .

What is audit log in node JS?

Audit Logs record every activity performed by any of your team members in your account.

How do you perform a CRUD operation in node JS?

CRUD (Create, Read, Update, Delete) operations allow you to work with the data stored in MongoDB. The CRUD operation documentation is categorized in two sections: Read Operations find and return documents stored within your MongoDB database. Write Operations insert, modify, or delete documents in your MongoDB database.


3 Answers

It's better to use a different schema having all the logs that you want to store for particular actions.

// schema
var schema = new Schema({
    actionType: {type: String, require: true},
    userId: { type: Schema.Types.ObjectId, required: true },
    userType: { type: String, required: true },
    message: { type: String, required: true },
    createdAt: { type: Date, default: Date.now },

}, options);

Here you can log your activity logs with

What action have been taken. Which user. And the message that you want to store with that action etc.

like image 125
Sachin Avatar answered Oct 19 '22 02:10

Sachin


You are talking about 'triggering'. But unfortunately "MongoDB does not support triggers".

For solving your issue simply create another collection and store the log information into that collection.

Reference :

  • does mongodb have the properties such as trigger and procedure in a relational database?
  • How to listen for changes to a MongoDB collection?
like image 4
Libu Mathew Avatar answered Oct 19 '22 03:10

Libu Mathew


If you are using mongoose module then there is method for logging all query.It'll log all queries on console.

mongoose.set('debug', true);

If you want to log in a file then use callback for this method

mongoose.set('debug', function (coll, method, query, doc [, options]) {
 //do your thing
});
like image 1
Vaibhav Patil Avatar answered Oct 19 '22 02:10

Vaibhav Patil