GithubHelp home page GithubHelp logo

benjbdev / mongoose-hidden Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mblarsen/mongoose-hidden

0.0 1.0 0.0 274 KB

A Mongoose schema plugin for filtering properties you usually do not want to sent client-side like passwords and IDs.

License: MIT License

JavaScript 99.85% Shell 0.15%

mongoose-hidden's Introduction

mongoose-hidden πŸ™ˆ

Build status codebeat badge Coverage status Known vulnerabilities PRs Welcome Monthly downloads NPM version

A Mongoose schema plugin that hooks into toJSON() and toObject() to allow hiding of properties you do not want sent client-side, like passwords and other secrets and sensitive information.

Contact me on Codementor

Install

npm i mongoose-hidden

Usage

A simple example that hides passwords:

let mongoose = require('mongoose')
let Schema = mongoose.Schema
let mongooseHidden = require('mongoose-hidden')()

let UserSchema = new Schema(
  name: String,
  password: { type: String, hide: true },
  email: String
)

UserSchema.plugin(mongooseHidden)

let User = mongoose.model('User', UserSchema)
let user = new User({
  name: 'Joe',
  email: '[email protected]',
  password: 'secret'
})

user.save(function() {
  console.log(user.toJSON()) // { name: 'Joe', email: '[email protected]' }
})

Property params: hide, hideJSON, hideObject

A property will be hidden in all cases when toJSON and toObject is invoked if the property parameter hide is used. Alternatively use hideJSON or hideObject to target either of the serialization functions.

let UserSchema = new Schema(
  ...
  password: { type: String, hideJSON: true }, // hidden for toJSON but not for toObject
  ...
)

The value of hide, hideJSON, and hideObject can be a callback with the following signature:

function (doc, ret) // same as the transform function callback

Option: hidden

If you find yourself hiding the same properties over and over again you can initialize the plugin with the hidden option.

There are two ways to set this up and they can be combined for more granular control.

// Passing constructor parameters
const mongooseHidden = require('mongoose-hidden')({ hidden: { _id: true, password: true } })
UserSchema.plugin(mongooseHidden)

// Passing plugin parameters when attaching to schema
const mongooseHidden = require('mongoose-hidden')()
UserSchema.plugin(mongooseHidden, { hidden: { _id: true, password: true } })

// Here they are used together
const mongooseHidden = require('mongoose-hidden')({ hidden: { _id: true, password: true } })
UserSchema.plugin(mongooseHidden, { hidden: { resetToken: true } })
PaymentSchema.plugin(mongooseHidden, { hidden: { _id: false, authToken: true } }) // unhides _id

//.. another example:

if (app === 'web') {
  UserSchema.plugin(mongooseHidden, { hidden: { _id: true, password: true } })
} else if (app == 'private-api') {
  UserSchema.plugin(mongooseHidden, { hidden: { password: true } })
} else {
  UserSchema.plugin(mongooseHidden)
}

Option: defaultHidden

By default _id and __v properties are hidden. You can override this behaviour, when you load the plugin:

let mongooseHidden = require('mongoose-hidden')({ defaultHidden: { password: true } })
UserSchema.plugin(mongooseHidden)

This effectively overrides the plugin defaults leaving only password hidden and _id and __v are left untouched.

Alternatively if you only want to unhide the params hidden by the plugin by default you can pass the plugin option autoHideJSON and autoHideObject with a value of false.

Option: virtuals

Hiding of virtuals can be done as well. Be sure to include the plugin after you turn on virtuals.

// By default in Mongoose virtuals will not be included. Turn on before enabling plugin.
schema.set('toJSON', { virtuals: true })
schema.set('toObject', { virtuals: true })

// Enable plugin
schema.plugin(mongooseHidden, { virtuals: { fullname: 'hideJSON' } })

The value of the virtuals key can be: hide, hideJSON and hideObject.

For nested virtuals use the path for the key above, e.g. 'nested.virtual': 'hideJSON'.

Note: If you don't turn on virtuals for toObject, fullname in the above example fullname will NOT be hidden despite its hideJSON value.

Option: applyRecursively

Off by default, but when turned on the plugin will attach itself to any child schemas as well.

Transform

The mongoose-hidden is written as a transform function. If you implement your own transform functions be sure to add them prior to applying the plugin. The plugin will then invoke that function before hiding properties.

let mongooseHidden = require('mongoose-hidden')()

// First define transform function
UserSchema.set('toJSON', {
  transform: function (doc, ret, opt) {
    ret['name'] = 'Mr ' + ret['name']
    return ret
  },
})

// Then apply plugin
UserSchema.plugin(mongooseHidden)

All names will now be prefixed with "Mr".

Changelog

See CHANGELOG.md

Limitations

  • Always set { getters: true, virtuals: true } before installing plugin if you want virtuals to be returned:
schema.set('toJSON', { getters: true, virtuals: true })
schema.plugin(require(mongooseHidden))

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Albert Hambardzumyan

⚠️ πŸ›

Awele

πŸ“–

Dan Trocchio

πŸ› ⚠️ πŸ’»

Michael BΓΈcker-Larsen

πŸ› πŸ’» 🚧 πŸ“–

Nathan Phillip Brink

πŸ“–

Pavel Evdokimov

πŸ› πŸ’» ⚠️

Thomas Sieverding

πŸ› πŸ’»

lally elias

πŸ› πŸ’»

mars

πŸ› πŸ’»

proswdev

πŸ› ⚠️ πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.