本文整理匯總了TypeScript中mongoose.Schema.add方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Schema.add方法的具體用法?TypeScript Schema.add怎麽用?TypeScript Schema.add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mongoose.Schema
的用法示例。
在下文中一共展示了Schema.add方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: timestampsPlugin
export function timestampsPlugin(schema: Schema) {
schema.add({ created_at: Date });
schema.add({ updated_at: Date });
schema.pre('save', function(next) {
if(! this.created_at) {
this.created_at = new Date();
}
this.updated_at = new Date();
next();
})
}
示例2:
export const RAMSchema = (schema: Object) => {
const result = new mongoose.Schema({
deleteInd: { type: Boolean, default: false },
resourceVersion: { type: String, default: '1' }
}, { timestamps: true });
result.add(schema);
return result;
};
示例3: slugPlugin
export function slugPlugin(schema: Schema, options) {
schema.add({ slug: String });
schema.pre('validate', function(next) {
if(! this.slug ) {
this.makeSlug();
}
next();
});
schema.path('slug').validate(function(value, respond) {
var query = this.constructor.count();
if(this.id) {
query.where('_id').ne(this.id);
}
// Make sure the slug is unique in this shop
if(options && options.uniqueShop) {
query.where('shop_id', getDocumentId(this.shop_id));
}
// Make sure it's unique for parent (used in categories)
if(options && options.uniqueParent) {
query.where('parent_id', getDocumentId(this.parent_id));
}
// Make sure it's unique for this user
if(options && options.uniqueUser) {
query.where('user_id', getDocumentId(this.user_id));
}
query.where('slug', this.slug);
return query.exec().then(function(count) {
if(count > 0) {
respond(false);
} else {
respond(true);
}
}, function() {
respond(false);
});
}, 'Slug must be unique');
schema.method('makeSlug', function() {
this.slug = slugify(this.title);
})
}
示例4:
_someId: mongoose.Schema.Types.ObjectId,
array: [],
ofString: [String],
ofNumber: [Number],
ofDates: [Date],
ofBuffer: [Buffer],
ofBoolean: [Boolean],
ofMixed: [mongoose.Schema.Types.Mixed],
ofObjectId: [mongoose.Schema.Types.ObjectId],
nested: {
stuff: { type: String, lowercase: true, trim: true }
}
});
schema.add({
mixedArray: {
type: [mongoose.Schema.Types.Mixed],
required: true
}
}, 'prefix');
schema.eachPath(function (path, type) {
path.toLowerCase();
type.sparse(true);
}).eachPath(cb);
schema.get('path');
schema.index({
name: 1,
binary: -1
}).index({}, {});
schema.indexes().slice();
schema.method('name', cb).method({
m1: cb,
m2: cb
示例5: Schema
import { Schema } from "mongoose";
export interface MessageRecordInterface {
messageName: string;
commandText: string;
}
export interface MessageHolderInterface {
name: string;
messages?: MessageRecordInterface[];
children?: MessageHolderInterface[];
}
export const MessageRecordSchema = new Schema({
messageName: String,
commandText: String
});
export const MessageHolderSchema = new Schema({
name: {
type: String,
required: true
},
messages: [MessageRecordSchema]
});
MessageHolderSchema.add({ children: [MessageHolderSchema] });
示例6: moderationPlugin
export function moderationPlugin(schema: Schema, opts?: ModerationPluginOptions) {
/*
* Add fields to entity
*/
schema.add({
moderation: {
is_approved: { type: Boolean, required: true, default: false },
is_refused: { type: Boolean, required: true, default: false },
is_deleted: { type: Boolean, required: true, default: false },
auto_approved: { type: Boolean, required: true, default: false },
history: [{
event: { type: String, enum: ['approved', 'refused', 'pending', 'deleted', 'undeleted'], required: true },
message: { type: String },
created_at: { type: Date },
_created_by: { type: Schema.Types.ObjectId, ref: 'User' },
}],
},
});
/*
* Post save trigger that automatically approves if the creator has
* the "auto-approve" permission.
*/
schema.pre('save', async function(this: ModeratedDocument) {
if (!this.isNew) {
return;
}
// check if _created_by is a contributor and auto-approve.
let user: UserDocument;
/* istanbul ignore if */
if (this.populated('_created_by')) {
user = this._created_by as UserDocument;
} else {
user = await state.models.User.findOne({ _id: this._created_by }).exec();
}
const resource = modelResourceMap[(this.constructor as any).modelName];
/* istanbul ignore if: Configuration error */
if (!resource) {
throw new Error('Tried to check moderation permission for unmapped entity "' + (this.constructor as any).modelName + '".');
}
const autoApprove = await acl.isAllowed(user.id, resource, 'auto-approve');
if (autoApprove) {
logger.info(null, '[moderationPlugin] Auto-approving %s "%s" for user <%s>.', (this.constructor as any).modelName, this.id, user.email);
const now = new Date();
this.moderation = {
is_approved: true,
is_refused: false,
is_deleted: false,
auto_approved: true,
history: [{ event: 'approved', created_at: now, _created_by: user }],
} as ModerationData;
} else {
this.moderation = {
is_approved: false,
is_refused: false,
is_deleted: false,
auto_approved: false,
history: [],
} as ModerationData;
}
});
/**
* Returns the query used for listing only approved entities.
*
* Note that this can *add* entities to the result.
*
* @param {Context} ctx Koa context
* @param {T} query Current query
* @returns {Promise<T>} Moderated query
*/
schema.statics.handleModerationQuery = async function<T>(ctx: Context, query: T): Promise<T> {
// no moderation filter requested, move on.
if (!ctx.query || !ctx.query.moderation) {
return addToQuery({ 'moderation.is_approved': true, 'moderation.is_deleted': false }, query);
}
if (!ctx.state.user) {
throw new ApiError('Must be logged in order to retrieve moderated items.').status(401);
}
const resource = modelResourceMap[this.modelName];
/* istanbul ignore if: configuration error */
if (!resource) {
logger.info(ctx.state, this);
throw new Error('Tried to check moderation permission for unmapped entity "' + this.modelName + '".');
}
const isModerator = await acl.isAllowed(ctx.state.user.id, resource, 'moderate');
if (!isModerator) {
throw new ApiError('Must be moderator in order to retrieved moderated items.').status(403);
}
const filters = ['refused', 'pending', 'auto_approved', 'manually_approved', 'deleted', 'all'];
if (!includes(filters, ctx.query.moderation)) {
throw new ApiError('Invalid moderation filter. Valid filters are: [ "' + filters.join('", "') + '" ].').status(400);
}
//.........這裏部分代碼省略.........
示例7: gameReferencePlugin
export function gameReferencePlugin(schema: Schema, options: GameReferenceOptions = {}) {
/*
* Add fields to entity
*/
if (options.isOptional) {
schema.add({ _game: { type: Schema.Types.ObjectId, ref: 'Game' } });
} else {
schema.add({ _game: { type: Schema.Types.ObjectId, required: 'Reference to game must be provided.', ref: 'Game' } });
}
/**
* Returns the query used for listing only non-restricted entities.
*
* @param {Application.Context} ctx Koa context
* @param {Array<any> | object} query Input query
* @return {Promise<Array<any> | object>} Output query
*/
schema.statics.applyRestrictions = async function<T>(this: ModelProperties, ctx: Context, query: T): Promise<T> {
const reference = modelReferenceMap[this.modelName];
const resource = modelResourceMap[this.modelName];
/* istanbul ignore if: Only applies when no restrictions are configured */
if (!config.vpdb.restrictions[reference] || isEmpty(config.vpdb.restrictions[reference].denyMpu)) {
return query;
}
const isModerator = ctx.state.user ? (await acl.isAllowed(ctx.state.user.id, resource, 'view-restricted')) : false;
// if moderator, don't filter.
if (isModerator) {
return query;
}
// find restricted games
const games = await state.models.Game.find({ 'ipdb.mpu': { $in: config.vpdb.restrictions[reference].denyMpu } }).exec();
if (ctx.state.user) {
return addToQuery({
$or: [
{ _created_by: ctx.state.user._id },
{ 'authors._user': ctx.state.user._id },
{ _game: { $nin: map(games, '_id') } },
],
}, query);
} else {
return addToQuery({ _game: { $nin: games.map(g => g._id) } }, query);
}
};
/**
* Returns the query for listing only non-restricted entities for a given game.
*
* @param {Application.Context} ctx Koa context
* @param {GameDocument} game Game to fetch entities for.
* @param {Array<any> | object} query Query to append
* @return {Promise<Array<any> | object | null>} Updated query on restriction, same without restriction and null if not logged.
*/
schema.statics.applyRestrictionsForGame = async function<T>(this: ModelProperties, ctx: Context, game: GameDocument, query: T): Promise<T | null> {
const reference = modelReferenceMap[this.modelName];
const resource = modelResourceMap[this.modelName];
// if not restricted, return same query (no filter)
if (!game.isRestricted(reference)) {
return query;
}
// if restricted by not logged, return null (no results)
if (!ctx.state.user) {
return null;
}
// now we have a user, check if either moderator or owner
const canViewRestricted = await acl.isAllowed(ctx.state.user.id, resource, 'view-restricted');
// if moderator, return same query (no filter)
if (canViewRestricted) {
return query;
}
// if no moderator, only returned owned or authored entities
return addToQuery({ $or: [{ _created_by: ctx.state.user._id }, { 'authors._user': ctx.state.user._id }] }, query);
};
/**
* Makes sure an API request can access the entity.
*
* @param {Application.Context} ctx Koa context
* @returns {Promise<GameReferenceDocument>} This entity
* @throws {ApiError} When access is denied
*/
schema.methods.assertRestrictedView = async function(this: GameReferenceDocument, ctx: Context): Promise<GameReferenceDocument> {
const game = this._game as GameDocument;
const modelName = (this.constructor as any).modelName;
const reference = modelReferenceMap[modelName];
const resource = modelResourceMap[modelName];
//.........這裏部分代碼省略.........