當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。