当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Schema.pre方法代码示例

本文整理汇总了TypeScript中mongoose.Schema.pre方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Schema.pre方法的具体用法?TypeScript Schema.pre怎么用?TypeScript Schema.pre使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mongoose.Schema的用法示例。


在下文中一共展示了Schema.pre方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: sortableTitlePlugin

export function sortableTitlePlugin(schema: Schema, opts: SortableTitleOptions = {}) {

	opts.src = opts.src || 'title';
	opts.dest = opts.dest || 'title_sortable';

	schema.pre('save', function(this: any, next: () => void) {
		if (this[opts.src]) {
			this[opts.dest] = this[opts.src].replace(/^((the|a|an)\s+)(.+)$/i, '$3, $2');
		}
		next();
	});
}
开发者ID:freezy,项目名称:node-vpdb,代码行数:12,代码来源:sortable.title.plugin.ts

示例2: timestampsPlugin

export function timestampsPlugin(schema: Schema) {
  schema.add({ created_at: Date });
  schema.add({ updated_at: Date });

  schema.pre('save', function(next) {
    if(! this.created_at) {
      this.created_at = new Date();
    }
    this.updated_at = new Date();
    next();
  })
}
开发者ID:dghijben,项目名称:dashboard,代码行数:12,代码来源:timestamps-plugin.ts

示例3: slugPlugin

export function slugPlugin(schema: Schema, options) {

  schema.add({ slug: String });

  schema.pre('validate', function(next) {
    if(! this.slug ) {
      this.makeSlug();
    }
    next();
  });

  schema.path('slug').validate(function(value, respond) {
    var query = this.constructor.count();

    if(this.id) {
      query.where('_id').ne(this.id);
    }

    // Make sure the slug is unique in this shop
    if(options && options.uniqueShop) {
      query.where('shop_id', getDocumentId(this.shop_id));
    }

    // Make sure it's unique for parent (used in categories)
    if(options && options.uniqueParent) {
      query.where('parent_id', getDocumentId(this.parent_id));
    }

    // Make sure it's unique for this user
    if(options && options.uniqueUser) {
      query.where('user_id', getDocumentId(this.user_id));
    }

    query.where('slug', this.slug);

    return query.exec().then(function(count) {
      if(count > 0) {
        respond(false);
      } else {
        respond(true);
      }
    }, function() {
      respond(false);
    });

  }, 'Slug must be unique');


  schema.method('makeSlug', function() {
    this.slug = slugify(this.title);
  })
}
开发者ID:kaka3004,项目名称:cms,代码行数:52,代码来源:slug-plugin.ts

示例4: Date

  },
  created: {
     type: Date,
     required: true,
     default: new Date()
  }
});
userSchema.methods.comparePassword = (password)=> {
	if ( ! this.password ) {
		return false;
	}
	return bcrypt.compareSync( password, this.password );
};
userSchema.pre('save', (next)=> {
  // check if password is present and is modified.
	if ( this.password && this.isModified('password') ) {
		this.password = hash_password(this.password);
	}
	next();
});

export interface IUserModel extends mongoose.Document {
  password: string,
  email:string,
  admin: boolean
  created: Date,
}

// Define & export Mongoose Model with Interface
export const User:mongoose.Model<IUserModel> = mongoose.model<IUserModel>('users', userSchema);
开发者ID:FazioNico,项目名称:nodejs-simple-graphql-ts,代码行数:30,代码来源:user.models.ts

示例5: function

  foreignField: 'target'
})

/**
 * Instances of sharings by users
 */
EventSchema.virtual('shares', {
  ref: CONST.ACTION_MODELS.SHARE,
  localField: '_id',
  foreignField: 'target'
})

/**
 * Creates a virtual 'averageRating' property
 */
EventSchema.virtual('averageRating').get(function() {
  return UTIL.getAverageRating(this)
})

EventSchema.pre('save', function(next: Function): void {
  // Set last modified time when values of only following props are changed
  UTIL.setUpdateTime(this, ['slug', 'title', 'content', 'excerpt', 'hero', 'tags', 'publish', 'isPublic', 'requireApproval', 'misc', 'destination', 'gallery', 'notes', 'gears', 'city', 'country', 'expenses', 'contacts', 'schedule', 'subsets'])
  this.wasNew = this.isNew

  next()
})

export { IEvent }

export default model<IEvent>('Event', EventSchema)
开发者ID:yeegr,项目名称:SingularJS,代码行数:30,代码来源:EventModel.ts

示例6: Schema

import cf from '../configs/server';
import {User} from './docs';

let UserSchema = new Schema({
   username: { type: String, required: true, index: { unique: true } },
   email: { type: String, required: true, index: { unique: true } },
   password: { type: String, required: true }
});

UserSchema.pre('save', function(next: any) {
    var user: User = this;
    if (!user.isModified('password')) return next();
 
    bcrypt.genSalt(cf.SALT_WORKER_VALUE, (err, salt) => {
        if (err) return next(err);

        bcrypt.hash(user.password, salt, (err, hash) => {
            if (err) return next(err);
            user.password = hash;
            next();
        });
    });
});

UserSchema.methods.comparePassword = function(candidatePassword: string, callback: (err: Error, isMatch?: boolean) => void) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return callback(err);
        callback(null, isMatch);
    });
};

开发者ID:tinganho,项目名称:api.codemanager.com,代码行数:30,代码来源:user.ts

示例7: function

        ref: "User",
        required: "Usuario es requerido"
    },
    postid: {
        type: String,
        default: "",
        ref: "Post",
        required: "El post es requerido"
    },
    username: {
        type: String,
        default: mongoose.Schema.Types.ObjectId.name,
        ref: "User",
        required: "Nombre de usuario es requerido"
    },
    like: {
        type: Number,
        default: 0,
    },
    dislike: {
        type: Number,
        default: 0,
    }
}, {collection: "comentario"});

ComentarioSchema.pre("save", function(this: IComentario, next) {
    this.createdAt = Date.now();
    next();
});

export let Comentario = mongoose.model<IComentario>("Comentario", ComentarioSchema);
开发者ID:maticorv,项目名称:mascotas2018_foro,代码行数:31,代码来源:comentario.schema.ts

示例8: function

}, 'reference is not valid')

// check if the stock required is present in the source
OrderSchema.pre('save', function (next: Function): void {
  let order = this

  PlaceModel.findOne({ _id: order.placeIdSource }).exec()
  .then((sourcePlace) => {
    if (sourcePlace.get('internalStock')) { // verification needed
      let errMsg2 = `Not enough stock in place: ${sourcePlace.get('name')}`
      let placeId = sourcePlace.get('_id')
      order.date = order.date || new Date()

      let placeStockState = new StockState(placeId, order.date)

      placeStockState.hasEnoughStock(order.stock)
      .then((hasEnough) => {
        if (hasEnough) {
          return next()
        } else {
          return next(new Error(errMsg2))
        }
      })

    } else {
      return next() // no need for verification since the source is external
    }
  }, (err) => next(err))
})

// check for user alerts on the stock
OrderSchema.post('save', (order, next) => {
开发者ID:chipp972,项目名称:stock_manager_api,代码行数:32,代码来源:order.ts

示例9: Date

const REFRESH_TOKEN_LIFETIME = 7 * 24 * 3600 * 1000;

let Schema = new mongoose.Schema({
    user_id : { type: String, required: true },
    refresh_token : { type : String},
    expiresAt : { type : Date, default : () => { return new Date(Date.now() + REFRESH_TOKEN_LIFETIME);}}
}, {
    timestamps: true
})

Schema.pre('save', async function(next) {
    var model = this;

    if (!model.isNew) return next();

    try {
        model.refresh_token = await generateRandomToken();
        next();
    } catch (exception) {
        next(exception);
    }
});

var generateRandomToken = async () => {
    return new Promise((resolve, reject) => {
        crypto.randomBytes(256, (error: Error, buf: Buffer) => {
            if (error) {
                return reject(new Error('Could not generate token'));
            }
            resolve(crypto.createHash('sha1').update(buf).digest('hex'));
        })
    });
开发者ID:rajivnarayana,项目名称:express-users,代码行数:32,代码来源:refresh-token-model.ts

示例10: moderationPlugin

export function moderationPlugin(schema: Schema, opts?: ModerationPluginOptions) {

	/*
	 * Add fields to entity
	 */
	schema.add({
		moderation: {
			is_approved: { type: Boolean, required: true, default: false },
			is_refused: { type: Boolean, required: true, default: false },
			is_deleted: { type: Boolean, required: true, default: false },
			auto_approved: { type: Boolean, required: true, default: false },
			history: [{
				event: { type: String, enum: ['approved', 'refused', 'pending', 'deleted', 'undeleted'], required: true },
				message: { type: String },
				created_at: { type: Date },
				_created_by: { type: Schema.Types.ObjectId, ref: 'User' },
			}],
		},
	});

	/*
	 * Post save trigger that automatically approves if the creator has
	 * the "auto-approve" permission.
	 */
	schema.pre('save', async function(this: ModeratedDocument) {
		if (!this.isNew) {
			return;
		}
		// check if _created_by is a contributor and auto-approve.
		let user: UserDocument;
		/* istanbul ignore if */
		if (this.populated('_created_by')) {
			user = this._created_by as UserDocument;
		} else {
			user = await state.models.User.findOne({ _id: this._created_by }).exec();
		}

		const resource = modelResourceMap[(this.constructor as any).modelName];
		/* istanbul ignore if: Configuration error */
		if (!resource) {
			throw new Error('Tried to check moderation permission for unmapped entity "' + (this.constructor as any).modelName + '".');
		}
		const autoApprove = await acl.isAllowed(user.id, resource, 'auto-approve');
		if (autoApprove) {
			logger.info(null, '[moderationPlugin] Auto-approving %s "%s" for user <%s>.', (this.constructor as any).modelName, this.id, user.email);
			const now = new Date();
			this.moderation = {
				is_approved: true,
				is_refused: false,
				is_deleted: false,
				auto_approved: true,
				history: [{ event: 'approved', created_at: now, _created_by: user }],
			} as ModerationData;
		} else {
			this.moderation = {
				is_approved: false,
				is_refused: false,
				is_deleted: false,
				auto_approved: false,
				history: [],
			} as ModerationData;
		}
	});

	/**
	 * Returns the query used for listing only approved entities.
	 *
	 * Note that this can *add* entities to the result.
	 *
	 * @param {Context} ctx Koa context
	 * @param {T} query Current query
	 * @returns {Promise<T>} Moderated query
	 */
	schema.statics.handleModerationQuery = async function<T>(ctx: Context, query: T): Promise<T> {

		// no moderation filter requested, move on.
		if (!ctx.query || !ctx.query.moderation) {
			return addToQuery({ 'moderation.is_approved': true, 'moderation.is_deleted': false }, query);
		}

		if (!ctx.state.user) {
			throw new ApiError('Must be logged in order to retrieve moderated items.').status(401);
		}
		const resource = modelResourceMap[this.modelName];
		/* istanbul ignore if: configuration error */
		if (!resource) {
			logger.info(ctx.state, this);
			throw new Error('Tried to check moderation permission for unmapped entity "' + this.modelName + '".');
		}

		const isModerator = await acl.isAllowed(ctx.state.user.id, resource, 'moderate');
		if (!isModerator) {
			throw new ApiError('Must be moderator in order to retrieved moderated items.').status(403);
		}

		const filters = ['refused', 'pending', 'auto_approved', 'manually_approved', 'deleted', 'all'];

		if (!includes(filters, ctx.query.moderation)) {
			throw new ApiError('Invalid moderation filter. Valid filters are: [ "' + filters.join('", "') + '" ].').status(400);
		}
//.........这里部分代码省略.........
开发者ID:freezy,项目名称:node-vpdb,代码行数:101,代码来源:moderation.plugin.ts


注:本文中的mongoose.Schema.pre方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。