パッケージの詳細

mongoose-hidden

mblarsen23kMIT1.9.1

Hides certain model properties when invoking toJSON or toObject.

mongoose, hidden, hide, property

readme

mongoose-hidden :see_no_evil:

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: 'joe@example.com',
  password: 'secret'
})

user.save(function() {
  console.log(user.toJSON()) // { name: 'Joe', email: 'joe@example.com' }
})

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!

更新履歴

Changelog

1.9.1

  • refactor: clean the codebase to make it easier to contribute
  • chore: upgrade mpath to 8.0

    1.9.0

  • feat: support for nested documents (issue #83)

  • chore: remove dependency on 'debug'

    1.8.1

  • fix bug introduced in 1.7.0 when populating relations using match (issue #75)

    1.8.0

  • reveret to old setPath of pre-1.7 but still use the mpath.set patching approach to make the client compatible with mpath.set

    1.7.0

  • replace custom setPath function with mpath.set (#69)

    1.6.2

  • added TypeScript definitions (thanks to @marshalys)

    1.6.0

Drop support for node 4 + 5, supported node version is Maintenance LTS. Version 1.5.4 is the last version to support older Node versions.

1.5.2

  • chore(package): update mongoose to version 5.0.0
  • chore(package): update mocha to version 5.0.0

    1.5.1

  • fix: 1.5.0 would add entries from the schema that were not in the original transform (thanks to @proswdev)

    1.5.0

refactor: Replaced get and delete path parts with mpath

I had wanted to get rid of the dot-path code for a long time. With this commit mpath is introduced. The same package used in Mongoose. It could not replace the set function, since it has no create functionality but only set.

I also cleaned up the options and test section so they are easier to reason about.

Overall a slimmer package.

1.4.2

Chore: Mocha dev dependency upgrade. New: Added license Fix: Minor style changes

1.4.1

Chore: Mongoose dev dependency upgrade

1.4.0

Support subdocument schema transformations (thanks to @Bajix)

1.3.0

New: Nested document can be a Schema (thanks to @lykmapipo)

1.2.0

Fixed regressions and added linting

1.1.0

Rewrote to getPathnames to rely on schema tree rather than scheme path. This should be more reliable.

1.0.0

First release. API unlikely to change.

0.9.2-3

Bug-fixes and code improvements.

0.9.0

Another internal rewrite to make the hide-logic more readable.

0.8.0

Internal rewrite to make nested documents and non-schema-values work.

0.7.0

Add hidden option.

0.6.4

Limited dependency version range for should.

0.6.2

Removed lodash dependency.

0.6.1

Fixes Issue #3

0.6.0

New: If a transform has already been set before loading plugin that function will be applied before applying plugin tranforms.

Other: Reduced code size.

0.4.0

Changed: Default virtuals value set to { } meaning id will no longer be hidden by default.

0.3.2

Fixed: id virtual was included by mistake in 0.3.1.

0.3.1

New: Introduced hiding of virtuals.

0.3.0

Changed: require('mongoose-hidden') is now require('mongoose-hidden')(defaults) with optional defaults.