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


TypeScript Schema.add方法代码示例

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


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

示例1: 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

示例2:

export const RAMSchema = (schema: Object) => {
  const result = new mongoose.Schema({
    deleteInd: { type: Boolean, default: false },
    resourceVersion: { type: String, default: '1' }
  }, { timestamps: true });
  result.add(schema);
  return result;
};
开发者ID:LachlanMcK,项目名称:RAM,代码行数:8,代码来源:base.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:

  _someId: mongoose.Schema.Types.ObjectId,
  array:      [],
  ofString:   [String],
  ofNumber:   [Number],
  ofDates:    [Date],
  ofBuffer:   [Buffer],
  ofBoolean:  [Boolean],
  ofMixed:    [mongoose.Schema.Types.Mixed],
  ofObjectId: [mongoose.Schema.Types.ObjectId],
  nested: {
    stuff: { type: String, lowercase: true, trim: true }
  }
});
schema.add({
  mixedArray: {
    type: [mongoose.Schema.Types.Mixed],
    required: true
  }
}, 'prefix');
schema.eachPath(function (path, type) {
  path.toLowerCase();
  type.sparse(true);
}).eachPath(cb);
schema.get('path');
schema.index({
  name: 1,
  binary: -1
}).index({}, {});
schema.indexes().slice();
schema.method('name', cb).method({
  m1: cb,
  m2: cb
开发者ID:RaySingerNZ,项目名称:DefinitelyTyped,代码行数:32,代码来源:mongoose-tests.ts

示例5: Schema

import { Schema } from "mongoose";

export interface MessageRecordInterface {
  messageName: string;
  commandText: string;
}

export interface MessageHolderInterface {
  name: string;
  messages?: MessageRecordInterface[];
  children?: MessageHolderInterface[];
}

export const MessageRecordSchema = new Schema({
  messageName: String,
  commandText: String
});
export const MessageHolderSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  messages: [MessageRecordSchema]
});
MessageHolderSchema.add({ children: [MessageHolderSchema] });
开发者ID:trflagg,项目名称:bargie,代码行数:25,代码来源:messageHolder.ts

示例6: 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

示例7: gameReferencePlugin

export function gameReferencePlugin(schema: Schema, options: GameReferenceOptions = {}) {

	/*
	 * Add fields to entity
	 */
	if (options.isOptional) {
		schema.add({ _game: { type: Schema.Types.ObjectId, ref: 'Game' } });
	} else {
		schema.add({ _game: { type: Schema.Types.ObjectId, required: 'Reference to game must be provided.', ref: 'Game' } });
	}

	/**
	 * Returns the query used for listing only non-restricted entities.
	 *
	 * @param {Application.Context} ctx Koa context
	 * @param {Array<any> | object} query Input query
	 * @return {Promise<Array<any> | object>} Output query
	 */
	schema.statics.applyRestrictions = async function<T>(this: ModelProperties, ctx: Context, query: T): Promise<T> {

		const reference = modelReferenceMap[this.modelName];
		const resource = modelResourceMap[this.modelName];

		/* istanbul ignore if: Only applies when no restrictions are configured */
		if (!config.vpdb.restrictions[reference] || isEmpty(config.vpdb.restrictions[reference].denyMpu)) {
			return query;
		}

		const isModerator = ctx.state.user ? (await acl.isAllowed(ctx.state.user.id, resource, 'view-restricted')) : false;

		// if moderator, don't filter.
		if (isModerator) {
			return query;
		}

		// find restricted games
		const games = await state.models.Game.find({ 'ipdb.mpu': { $in: config.vpdb.restrictions[reference].denyMpu } }).exec();

		if (ctx.state.user) {
			return addToQuery({
				$or: [
					{ _created_by: ctx.state.user._id },
					{ 'authors._user': ctx.state.user._id },
					{ _game: { $nin: map(games, '_id') } },
				],
			}, query);

		} else {
			return addToQuery({ _game: { $nin: games.map(g => g._id) } }, query);
		}
	};

	/**
	 * Returns the query for listing only non-restricted entities for a given game.
	 *
	 * @param {Application.Context} ctx Koa context
	 * @param {GameDocument} game Game to fetch entities for.
	 * @param {Array<any> | object} query Query to append
	 * @return {Promise<Array<any> | object | null>} Updated query on restriction, same without restriction and null if not logged.
	 */
	schema.statics.applyRestrictionsForGame = async function<T>(this: ModelProperties, ctx: Context, game: GameDocument, query: T): Promise<T | null> {

		const reference = modelReferenceMap[this.modelName];
		const resource = modelResourceMap[this.modelName];

		// if not restricted, return same query (no filter)
		if (!game.isRestricted(reference)) {
			return query;
		}

		// if restricted by not logged, return null (no results)
		if (!ctx.state.user) {
			return null;
		}

		// now we have a user, check if either moderator or owner
		const canViewRestricted = await acl.isAllowed(ctx.state.user.id, resource, 'view-restricted');
		// if moderator, return same query (no filter)
		if (canViewRestricted) {
			return query;
		}

		// if no moderator, only returned owned or authored entities
		return addToQuery({ $or: [{ _created_by: ctx.state.user._id }, { 'authors._user': ctx.state.user._id }] }, query);
	};

	/**
	 * Makes sure an API request can access the entity.
	 *
	 * @param {Application.Context} ctx Koa context
	 * @returns {Promise<GameReferenceDocument>} This entity
	 * @throws {ApiError} When access is denied
	 */
	schema.methods.assertRestrictedView = async function(this: GameReferenceDocument, ctx: Context): Promise<GameReferenceDocument> {

		const game = this._game as GameDocument;
		const modelName = (this.constructor as any).modelName;
		const reference = modelReferenceMap[modelName];
		const resource = modelResourceMap[modelName];

//.........这里部分代码省略.........
开发者ID:freezy,项目名称:node-vpdb,代码行数:101,代码来源:game.reference.plugin.ts


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