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


TypeScript Schema.post方法代码示例

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


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

示例1: function

  foreignField: '_id',
  justOne: true
})

LikeSchema.virtual('TargetModel', {
  ref: (doc: IAction) => doc.targetRef,
  localField: 'target',
  foreignField: '_id',
  justOne: true
})

LikeSchema.post('save', function(action: IAction) {
  let TargetModel = UTIL.getModelFromName(action.targetRef)

  TargetModel
  .findByIdAndUpdate(action.target, {$inc: {likeCount: 1}})
  .then()
  .catch((err: NativeError) => {
    console.log(err)
  })
})

LikeSchema.post('findOneAndRemove', function(action: IAction) {
  if (action) {
    let TargetModel = UTIL.getModelFromName(action.targetRef)
    
    TargetModel
    .findByIdAndUpdate(action.target, {$inc: {likeCount: -1}})
    .then()
    .catch((err: NativeError) => {
      console.log(err)
    })
开发者ID:yeegr,项目名称:SingularJS,代码行数:32,代码来源:LikeModel.ts

示例2: function

schema.index({
  name: 1,
  binary: -1
}).index({}, {});
schema.indexes().slice();
schema.method('name', cb).method({
  m1: cb,
  m2: cb
});
schema.path('a', mongoose.Schema.Types.Buffer).path('a');
schema.pathType('m1').toLowerCase();
schema.plugin(function (schema, opts) {
  schema.get('path');
  opts.hasOwnProperty('');
}).plugin(cb, {opts: true});
schema.post('post', function (doc) {}).post('post', function (doc, next) {
  next(new Error());
});
schema.queue('m1', [1, 2, 3]).queue('m2', [[]]);
schema.remove('path');
schema.remove(['path1', 'path2', 'path3']);
schema.requiredPaths(true)[0].toLowerCase();
schema.set('key', 999).set('key');
schema.static('static', cb).static({
  s1: cb,
  s2: cb
});
schema.virtual('virt', {}).applyGetters({}, {});
schema.virtualpath('path').applyGetters({}, {});
/* static properties */
mongoose.Schema.indexTypes[0].toLowerCase();
开发者ID:RaySingerNZ,项目名称:DefinitelyTyped,代码行数:31,代码来源:mongoose-tests.ts

示例3: getModel

export function metricsPlugin<T>(schema: Schema, options: MetricsOptions = {}) {

	const getId = options.getId || (doc => doc.id);

	if (options.hasChildren) {
		schema.post('findOne', onFindOne);
	}

	schema.virtual('hasRelations').get(() => true);
	schema.methods.$updateRelations = function(this: MetricsDocument, parentModel: string, parentId: string, absPath: string, queryPath: string, arrayFilters: ArrayFilter[]) {
		this.$$parentModel = parentModel;
		this.$$parentId = parentId;
		this.$$cachePath = absPath.replace(/\.\d+/g, '');
		this.$$queryArrayFilters = arrayFilters;
		if (/\.\d+$/.test(absPath)) {
			this.$$queryPath = queryPath.replace(/\.\d+$/g, `.$[id${this._id.toString()}]`);
			this.$$queryArrayFilters.push({ [`id${this._id.toString()}._id`]: this._id });
		}
	};

	schema.methods.getParentModel = function(this: MetricsDocument): string {
		return this.$$parentModel || (this.constructor as any).modelName;
	};

	schema.methods.getParentId = function(this: MetricsDocument): string {
		return this.$$parentId || this.id;
	};

	schema.methods.getCachePath = function(this: MetricsDocument, opts: {prefix?: string, suffix?: string} = {}) {
		const path = opts.prefix && this.$$cachePath
			? `${opts.prefix}.${this.$$cachePath}`
			: opts.prefix || this.$$cachePath || '';
		return path && opts.suffix ? `${path}.${opts.suffix}` : path || opts.suffix;
	};

	/**
	 * Increments a counter.
	 *
	 * @param {string} counterName Property to increment, e.g. 'view'
	 * @param {number} [value=1] How much to increment. Use a negative value for decrement
	 * @returns {Promise}
	 */
	schema.methods.incrementCounter = async function(this: MetricsDocument, counterName: string, value: number = 1): Promise<void> {
		const q: any = {
			$inc: { [getCounterUpdatePath(this, counterName)]: value },
		};
		if (options.hotness) {
			q.metrics = q.metrics || {};
			Object.keys(options.hotness).forEach(metric => {
				const hotness = options.hotness[metric];
				let score = 0;
				Object.keys(hotness).forEach(variable => {
					const factor = hotness[variable];
					if (this.counter[variable]) {
						score += factor * (this.counter[variable] + (variable === counterName ? value : 0));
					}
				});
				q.metrics[metric] = Math.log(Math.max(score, 1));
			});
		}

		// update cache
		await apiCache.incrementCounter(getCacheModelName(this), getId(this), counterName, value);

		// update db
		const conditions = { id: this.getParentId() || this.id };
		const arrayFilters = this.$$queryArrayFilters || [];
		await getModel(this).updateOne(conditions, q, { arrayFilters }).exec();
	};

	/**
	 * Increments a counter, but without updating any other metric.
	 * Currently only used by the cache middleware.
	 *
	 * @param {string} entityId ID of the entity to update
	 * @param {string} counterName Name of the counter, e.g. "views"
	 * @param {number} [value=1] How much to increment. Use a negative value for decrement
	 */
	schema.statics.incrementCounter = async function(this: ModelProperties, entityId: string, counterName: string, value: number = 1): Promise<void> {
		// update cache
		await apiCache.incrementCounter(this.modelName.toLowerCase(), entityId, counterName, value);
		// update db
		await state.getModel(this.modelName).findOneAndUpdate({ id: entityId }, { $inc: { ['counter.' + counterName]: value } }).exec();
	};
}
开发者ID:freezy,项目名称:node-vpdb,代码行数:85,代码来源:metrics.plugin.ts

示例4: Schema

export interface ILearnModel extends pg.models.ILearn, Document{
    photos: IPhotoModel[],
    _id: any
}

let VideoSchema = new Schema({
    name: String,
    url: String,
    order: Number
});

let LearnSchema = new Schema({
    name: String,
    order:Number,
    photos: [PhotoSchema],
   videos: [VideoSchema],
});

LearnSchema.post('remove', (learn:ILearnModel) => {
    try {
        learn.photos.forEach((photo:any)=> {
            photo.remove();
        });

    } catch(err) {
        console.log(err);
    }
});

export var Learn = model<ILearnModel>('Learn', LearnSchema);
开发者ID:galyna,项目名称:PalamarGroup,代码行数:30,代码来源:learn.ts

示例5: Date

      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) => {
  // alertCheck(order)
  next()
})

OrderSchema.pre('remove', function (next: Function): void {
  return next(new Error('Cannot delete an order; update order\'s state'))
})

export let OrderModel = mongoose.model<Order>(modelName, OrderSchema)
开发者ID:chipp972,项目名称:stock_manager_api,代码行数:30,代码来源:order.ts

示例6: function

});

// TODO validate logo

//-----------------------------------------------------------------------------
// METHODS
//-----------------------------------------------------------------------------

gameSchema.methods.isRestricted = function(what: 'release' | 'backglass'): boolean {
	return Game.isRestricted(this, what);
};

//-----------------------------------------------------------------------------
// TRIGGERS
//-----------------------------------------------------------------------------
gameSchema.post('remove', async function() {
	// remove reference separately so post-hooks are run
	const ratings = await state.models.Rating.find({ '_ref.game': this._id }).exec();
	for (const rating of ratings) {
		await rating.remove();
	}
	const stars = await state.models.Star.find({ '_ref.game': this._id }).exec();
	for (const star of stars) {
		await star.remove();
	}
	const media = await state.models.Medium.find({ '_ref.game': this._id }).exec();
	for (const medium of media) {
		await medium.remove();
	}
});
开发者ID:freezy,项目名称:node-vpdb,代码行数:30,代码来源:game.schema.ts

示例7: fileReferencePlugin

export function fileReferencePlugin(schema: Schema, options: FileReferenceOptions = {}) {

	// filter ignored paths
	const paths = pickBy(traversePaths(schema), schemaType => schemaType.options && schemaType.options.ref && schemaType.options.ref === 'File');
	const fileRefs = omitBy(paths, (schemaType, path) => options.ignore && options.ignore.includes(path));

	//-----------------------------------------------------------------------------
	// VALIDATIONS
	//-----------------------------------------------------------------------------
	keys(fileRefs).forEach(path => {

		schema.path(path).validate(async function(fileId: any) {

			if (!fileId || !this._created_by) {
				return true;
			}
			const file = await state.models.File.findOne({ _id: fileId._id || fileId.toString() }).exec();
			if (!file) {
				return true;
			}

			if (this.isNew && file.is_active) {
				this.invalidate(path, 'Cannot reference active files. If a file is active that means that is has been referenced elsewhere, in which case you cannot reference it again.', file.id);
			}
			return true;

		});
	});

	/**
	 * Sets the referenced files to active. Call this after creating a new
	 * instance.
	 *
	 * Note that only inactive files are activated, already activated files
	 * are ignored.
	 *
	 * @returns {Promise.<String[]>} File IDs that have been activated.
	 */
	schema.methods.activateFiles = async function(requestState: RequestState): Promise<string[]> {
		const ids: string[] = [];
		const objPaths = keys(explodePaths(this, fileRefs));
		objPaths.forEach(path => {
			const id = get(this, path);
			if (id) {
				ids.push(id._id || id);
			}
		});
		const files = await state.models.File.find({ _id: { $in: ids }, is_active: false }).exec();
		for (const file of files) {
			await file.switchToActive(requestState);
		}
		await this.populate(objPaths.join(' ')).execPopulate();
		return files.map(f => f.id);
	};

	/**
	 * Remove file references from database
	 */
	schema.post('remove', async (obj: Document) => {

		const objPaths = keys(explodePaths(obj, fileRefs));
		const ids: string[] = [];
		objPaths.forEach(path => {
			const id = get(obj, path + '._id');
			if (id) {
				ids.push(id);
			}
		});
		const files = await state.models.File.find({ _id: { $in: ids } }).exec();

		// remove file references from db
		for (const file of files) {
			logger.debug(null, '[fileReferencePlugin] Removing referenced file %s', file.toDetailedString());
			await file.remove();
		}
	});
}
开发者ID:freezy,项目名称:node-vpdb,代码行数:77,代码来源:file.reference.plugin.ts

示例8: Schema

    _id: any
}


let VideoSchema = new Schema({
    name: String,
    url: String,
    order: Number
});

let TransformSchema = new Schema({
    name: String,
    order:Number,
    videos: [VideoSchema],
    photos: [PhotoSchema],
   
});

 TransformSchema.post('remove', (transform:ITransformModel) => {
    try {
        transform.photos.forEach((photo:any)=> {
            photo.remove();
        });
     
    } catch(err) {
        console.log(err);
    }
});

export var Transform = model<ITransformModel>('Transform', TransformSchema);
开发者ID:galyna,项目名称:PalamarGroup,代码行数:30,代码来源:transform.ts

示例9: next

  next()
})

CommentSchema.post('save', function(comment: IComment) {
  let CreatorModel = UTIL.getModelFromName(comment.creatorRef),
    TargetModel = UTIL.getModelFromName(comment.targetRef),
    wasNew = this.wasNew

  TargetModel
  .findById(comment.target)
  .then((doc: any) => {
    if (wasNew) {
      UTIL.addComment(doc, comment.rating)      

      CreatorModel
      .findByIdAndUpdate(comment.creator, {$inc: {commentCount: 1}})
      .then()
      .catch((err: NativeError) => {
        console.log(err)
      })
    } else {
      UTIL.updateComment(doc, comment.diff)
    }
  })
  .catch((err: NativeError) => {
    console.log(err)
  })
})

CommentSchema.post('findOneAndRemove', function(comment: IComment) {
  let CreatorModel = UTIL.getModelFromName(comment.creatorRef),
开发者ID:yeegr,项目名称:SingularJS,代码行数:31,代码来源:CommentModel.ts

示例10: function

    virtuals: false
  }
})

DownloadSchema.virtual('CreatorModel', {
  ref: (doc: IAction) => doc.creatorRef,
  localField: 'creator',
  foreignField: '_id',
  justOne: true
})

DownloadSchema.virtual('TargetModel', {
  ref: (doc: IAction) => doc.targetRef,
  localField: 'target',
  foreignField: '_id',
  justOne: true
})

DownloadSchema.post('save', function(action: IAction) {
  let TargetModel = UTIL.getModelFromName(action.targetRef)

  TargetModel
  .findByIdAndUpdate(action.target, {$inc: {downloadCount: 1}})
  .then()
  .catch((err: NativeError) => {
    console.log(err)
  })
})

export default model<IAction>('Download', DownloadSchema)
开发者ID:yeegr,项目名称:SingularJS,代码行数:30,代码来源:DownloadModel.ts


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