Hide password in MongoDb

Abayomi Ogunnusi - Jun 23 '22 - - Dev Community

As developers, there are times or reasons why we don't want our passwords to be accessible by default when creating our APIs. Here are some ways we can hide our passwords.

hide


🎯 Prerequisite

NodeJs + Express Knowledge
MongoDb + Mongoose [Basic CRUD functionality knowledge]


In this post, I am using mongoose. Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box Read more here. Basically, mongoose is an ODM [Object Data Modelling] library that helps to write simple queries other than the native/raw MongoDb queries.

Method 1

Image description
Here we are using the mongoose to find all users and removing all passwords using the select. The - sign basically negates the function. It means ignore the password from the objects being fetched.


Method 2

Image description
Here we de-structured response object coming from our database using javascript spread operator and ignored the password.


Method 3

Image description
This method 3 is an alternative way of writing Method 1 using the select query method.


Conclusion

I hope this post was helpful. Thanks for reading.

Resources

Mongoose Documentation

Javascript Spread syntax - MDN

Mongoose-npmjs

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .