本文整理匯總了TypeScript中mongoose.Schema.virtual方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Schema.virtual方法的具體用法?TypeScript Schema.virtual怎麽用?TypeScript Schema.virtual使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mongoose.Schema
的用法示例。
在下文中一共展示了Schema.virtual方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: setUpSchema
function setUpSchema({schema, virtuals}: MongooseSchema, options?: mongoose.SchemaOptions) {
const mongooseSchema = new mongoose.Schema(schema, options);
for (const [key, options] of virtuals.entries()) {
mongooseSchema.virtual(key, options);
}
return mongooseSchema;
}
示例2: function
virtuals: false
}
})
LikeSchema.index({
creator: 1,
creatorRef: 1,
target: 1,
targetRef: 1
}, {
unique: true
})
LikeSchema.virtual('CreatorModel', {
ref: (doc: IAction) => doc.creatorRef,
localField: 'creator',
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}})
示例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: function
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();
mongoose.Schema.reserved.hasOwnProperty('');
/* inherited properties */
schema.addListener('e', cb);
/* practical examples */
var animalSchema = new mongoose.Schema({
name: String,
type: String
});
animalSchema.methods.findSimilarTypes = function (cb: any) {
return this.model('Aminal').find({ type: this.type }, cb);
};
var Animal: any = mongoose.model('Animal', animalSchema);
示例5: RegExp
userSchema.path('email').validate(function (email) {
var email_regexp = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "g");
return email_regexp.test(email);
}, 'Invalid email');
/**
* Defines a virtual setter for a password field. This allows us to
* transparently deal with password hashing even though there is no
* password attribute defined in the schema.
*
* Passwords are hashed with SHA256 and a 32-bytes salt.
*
* @author Gabriel Malkas
*/
userSchema.virtual('password').set(function (password) {
var crypto = require('crypto');
this._password = password;
this.passwordSalt = crypto.randomBytes(32);
this.passwordHash = hashPassword(password, this.passwordSalt);
});
/**
* Defines a virtual setter for a password confirmation field.
*/
userSchema.virtual('passwordConfirmation').set(function (password) {
this._passwordConfirmation = password;
});
/**
示例6: Number
productId: {
type: String,
required: `Product Id can't be blank.`
},
userId: {
type: String,
required: `User id can't be blank.`
},
cost: {
type: Number,
required: `Cost can't be blank.`
}
})
// Duplicate the ID field.
ratingSchema.virtual('id').get(function() {
return this._id
})
// Ensure virtual fields are serialised.
ratingSchema.set('toJSON', {
virtuals: true
})
ratingSchema.path('productId').required(true, `Prodcut id can't be blank.`)
ratingSchema.path('userId').required(true, `User id can't be blank.`)
ratingSchema.path('cost').validate(function(price) {
return Number(price).toString() === price.toString()
}, `Cost must be a float number.`)
const Rating = mongoose.model('Rating', ratingSchema)
示例7:
// outgoing / response comment
comment: {
type: String
}
}, {
toObject: {
virtuals: false
},
toJSON: {
virtuals: false
}
})
ActivitySchema.virtual('CreatorModel', {
ref: (doc: IActivity) => doc.creatorRef,
localField: 'creator',
foreignField: '_id',
justOne: true
})
ActivitySchema.virtual('TargetModel', {
ref: (doc: IActivity) => doc.targetRef,
localField: 'target',
foreignField: '_id',
justOne: true
})
ActivitySchema.virtual('HandlerModel', {
ref: (doc: IActivity) => doc.handlerRef,
localField: 'handler',
foreignField: '_id',
justOne: true
示例8: Schema
export interface UserModel extends MetricsModel<UserDocument> { }
export const userSchema = new Schema(userFields, { toObject: { virtuals: true, versionKey: false } });
userSchema.index({ name: 'text', username: 'text', email: 'text' });
//-----------------------------------------------------------------------------
// PLUGINS
//-----------------------------------------------------------------------------
userSchema.plugin(uniqueValidator, { message: 'The {PATH} "{VALUE}" is already taken.' });
userSchema.plugin(metricsPlugin);
//-----------------------------------------------------------------------------
// VIRTUALS
//-----------------------------------------------------------------------------
userSchema.virtual('password')
.set(function(password: string) {
this._password = password;
this.password_salt = this.makeSalt();
this.password_hash = this.hashPassword(password);
})
.get(function() {
return this._password;
});
userSchema.virtual('planConfig')
.get(function() {
let plan = find(config.vpdb.quota.plans, p => p.id === this._plan);
if (!plan) {
logger.warn(null, '[User.planConfig] Cannot find plan "%s" for user "%s" in server config.', this._plan, this.email);
plan = find(config.vpdb.quota.plans, p => p.id === config.vpdb.quota.defaultPlan);
示例9:
* Schema indexes:
* schema.index({fieldName: <1;-1>, ...})
*/
/*
* Schema virtuals:
* schema.virtual('virtualName').get(function() {...}) // NO ARROW FUNCTION OR EMPTY THIS OBJECT
* schema.virtual('virtualName').set(function(...) {...})
* schema1.virtual('virtualName', {
* ref: 'schema2Name', // The model to use
* localField: 'schema1Field', // Find docs in schema2 where `schema1Field` ( in schema1,
* // SHOULD BE A FIELD WITH AN UNIQUE INDEX )
* foreignField: 'schema2Field' // is equal to `schema2Field` ( in schema2 )
* });
*/
UserSchema.virtual('name').get(function () {
return this.firstName + ' ' + this.lastName;
});
/**
* Interfaces for TypeScript:
* - Add the virtuals as optional properties
* - The first one will mostly be used for creation in the Front-End
* - The second one will be used in both Back and Front
*/
export interface User {
firstName: string;
lastName: string;
name?: string;
email: string;
role: string;
示例10: function
/**
* Removes password from return JSON
*/
PlatformSchema.set('toJSON', {
transform: function(doc: any, ret: any, opt: any) {
delete ret.password
return ret
}
})
/**
* Activities handled | responded by user
*/
PlatformSchema.virtual('activities', {
ref: 'Activity',
localField: '_id',
foreignField: 'handler'
})
/**
* Hash incoming password with salt and
* compare it to stored password hash
*
* @class PlatformSchema
* @method comparePassword
* @param {string} candidatePassword
* @param {function} callback
* @returns {void}
*/
PlatformSchema.methods.comparePassword = function(candidatePassword: string, callback: Function): void {
bcrypt