本文整理汇总了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)
})
示例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();
示例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();
};
}
示例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);
示例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)
示例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();
}
});
示例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();
}
});
}
示例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);
示例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),
示例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)