How to override DB methods in .mongoshrc.js

In “mongo” using .mongorc.js it was possible to do this:

DB.prototype.dropDatabase = function() {
  print('Dropping databases is not authorized')

But in “mongosh” using .mongoshrc.js it doesn’t have DB object, and db (lowercase) doesn’t seems to work the same way:

db.prototype.dropDatabase = function() {
  print('Dropping databases is not authorized')

How could I override dropDatabase method in the new mongo shell?

You should be able to do that with:

db.__proto__.dropDatabase = () => console.log('Dropping databases is not authorized')

However, I would recommend against overriding prototype methods as that might cause the shell to behave unexpectedly.

The best and most secure way to prevent someone (or yourself) from dropping a database is to not give them dbAdmin role. Even when overriding the dropDatabase helper, it’s still possible to drop a database with:

db.runCommand( { dropDatabase: 1 } )

Indeed you are right.
About the security issues, the dropDatabase() in this case is to some legacy really old Mongo automation that won’t cause any risk in production.
But as we’re upgrading Mongo, we’ll take into consideration.
Thanks Massimiliano.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.