Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * MongooseJS plugin to auto-populate the _createdBy and _updatedBy document values (If they exist in the schema)
- */
- 'use strict'
- import _ from 'moar-lodash'
- import * as appRoot from 'app-root-path'
- import Mongoose from 'mongoose'
- const log = appRoot.require('./dist/lib/utils/logger')({ plugin: 'Mongoose ByAccount'})
- const accountHelper = appRoot.require('./dist/lib/helpers/account')
- module.exports = ( schema, options ) => {
- schema.pre( 'save', function( next ) {
- // Only continue if the schema has createdBy or updatedBy
- if( _.isObject( schema.paths._createdBy ) || _.isObject( schema.paths._updatedBy ) ) {
- // Retrieve the account ID and username
- const accountId = accountHelper.getAccount( '_id' )
- const accountUn = accountHelper.getAccount( 'username' ) || 'Unknown'
- // If no account ID is found, then just return void, to avoid updating the updated/created by
- if( ! accountId ) {
- log.warn( `Unable to populate _createdBy - No account ID set in the Account Helper` )
- }
- // If Mongooses isNew value is true then its being created
- else if( this.isNew ) {
- if( _.isObject( schema.paths._createdBy ) ) {
- log.debug( `Schema item _createdBy found - Populating with ${accountId} (Username: ${accountUn})` )
- this._createdBy = accountId
- this.markModified( '_createdBy' )
- }
- else {
- log.debug( `Document is being created, but no _createdBy object found in schema` )
- }
- }
- // No isNew value, so its being updated
- else {
- if( _.isObject( schema.paths._updatedBy ) ) {
- log.debug( `Schema item _updatedBy found - Populating with ${accountId} (Username: ${accountUn})` )
- this._updatedBy = accountId
- this.markModified( '_updatedBy' )
- }
- else {
- log.debug( `Document is being updated, but no _updatedBy object found in schema` )
- }
- }
- }
- next()
- } )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement