How to get free YouTube subscribers, likes and views?
Get Free YouTube Subscribers, Views and Likes

Authentication in Node.js - #8 Protected Fields in Mongoose

Follow
Code Realm

Oftentimes, when building the user's endpoint in a REST API (typically, /me or /home), you'd want to only expose a subset of the fields stored in the database table or collection. Specifically, you'd need to hide sensitive fields including the password hash, as well as meta data such as the version key, from the server response. In Mongoose, there are several ways to achieve that.

First, you could pass a string with spaceseparated fields to the select() method on the model, effectively whitelisting the fields to be queried. Alternatively, you could blacklist certain fields in select() by prepending them with a dash, or using exclude() instead. Yet another approach would be to hook into the schema options with the set() method. One option is toJSON which gets invoked when the toJSON method is invoked on the document. Keep in mind that this approach won't work if you tack on lean() on the query, as this will return a POJO (plainold JavaScript object) rather than a Mongoose document. If you prefer to fetch a POJO for better performance, you can list the fields in either select() or exclude().

Protecting fields in Mongoose https://stackoverflow.com/q/12096262

Mongoose schema options https://mongoosejs.com/docs/guide.htm...

GitHub repo https://github.com/alex996/nodeauth

posted by CydayCitambumyy