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


TypeScript Schema.virtual方法代码示例

本文整理汇总了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;
}
开发者ID:Romakita,项目名称:ts-express-decorators,代码行数:9,代码来源:createSchema.ts

示例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}})
开发者ID:yeegr,项目名称:SingularJS,代码行数:32,代码来源:LikeModel.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: 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);
开发者ID:RaySingerNZ,项目名称:DefinitelyTyped,代码行数:31,代码来源:mongoose-tests.ts

示例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;
    });

    /**
开发者ID:gmalkas,项目名称:genovesa,代码行数:31,代码来源:user.ts

示例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)
开发者ID:Julianhm9612,项目名称:coolstore-microservices,代码行数:31,代码来源:rating.ts

示例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
开发者ID:yeegr,项目名称:SingularJS,代码行数:32,代码来源:ActivityModel.ts

示例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);
开发者ID:freezy,项目名称:node-vpdb,代码行数:30,代码来源:user.schema.ts

示例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;
开发者ID:flowg,项目名称:Locutus,代码行数:31,代码来源:__User.ts

示例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
开发者ID:yeegr,项目名称:SingularJS,代码行数:31,代码来源:PlatformModel.ts


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