Advertisement
Guest User

Untitled

a guest
Feb 16th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * MongooseJS plugin to auto-populate the _createdBy and _updatedBy document values (If they exist in the schema)
  3.  */
  4. 'use strict'
  5.  
  6. import _ from 'moar-lodash'
  7. import * as appRoot from 'app-root-path'
  8. import Mongoose from 'mongoose'
  9.  
  10. const log           = appRoot.require('./dist/lib/utils/logger')({ plugin: 'Mongoose ByAccount'})
  11. const accountHelper = appRoot.require('./dist/lib/helpers/account')
  12.  
  13. module.exports = ( schema, options ) => {
  14.     // If the schema has a _createdBy..
  15.     if( _.isObject( schema.paths._createdBy ) ) {
  16.         log.debug( `Schema item _createdBy found` )
  17.  
  18.         schema.pre( 'save', function( next ) {
  19.             if( ! accountHelper.getAccount( '_id' ) ) {
  20.                 log.warn( `Unable to populate _createdBy - No account ID set in the Account Helper` )
  21.             }
  22.             else {
  23.                 this._createdBy = accountHelper.getAccount( '_id' )
  24.                 this.markModified( '_createdBy' )
  25.             }
  26.  
  27.             next()
  28.         } )
  29.     }
  30.  
  31.     // If the schema has a _updatedBy...
  32.     if( _.isObject( schema.paths._updatedBy ) ) {
  33.         log.debug( `Schema item _updatedBy found` )
  34.  
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement