本文整理汇总了TypeScript中mongoose.Schema.path方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Schema.path方法的具体用法?TypeScript Schema.path怎么用?TypeScript Schema.path使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mongoose.Schema
的用法示例。
在下文中一共展示了Schema.path方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: if
schema.eachPath((path, schemaType: any) => {
let validateFunction: (doc: Document, path: string, refModelName: string, values: any[], conditions: {[key: string]: any}) => Promise<boolean> = null;
let refModelName: string = null;
let conditions = {};
if (fields.length > 0 && !fields.includes(path)) {
return;
}
if (schemaType.options && schemaType.options.ref) {
validateFunction = validateId;
refModelName = schemaType.options.ref;
if (schemaType.options.refConditions) {
conditions = schemaType.options.refConditions;
}
} else if (schemaType.caster && schemaType.caster.instance && schemaType.caster.options && schemaType.caster.options.ref) {
validateFunction = validateIdArray;
refModelName = schemaType.caster.options.ref;
if (schemaType.caster.options.refConditions) {
conditions = schemaType.caster.options.refConditions;
}
}
if (validateFunction) {
schema.path(path).validate(async function(value: any) {
return validateFunction(this, path, refModelName, value, conditions);
}, message);
}
});
示例2: 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);
})
}
示例3: keys
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;
});
});
示例4: validateLocalStrategyPassword
},
updated: {
type: Date,
default: Date.now()
},
created: {
type: Date,
default: Date.now()
},
enabled: {
type: Boolean,
default: true
}
}, { collection: "users" });
UserSchema.path("password").validate(function (value: string) {
return validateLocalStrategyPassword(value);
}, "La contraseĂąa debe ser mayor a 6 caracteres");
/**
* Trigger antes de guardar, si el password se modifico hay que encriptarlo
*/
UserSchema.pre("save", function (this: IUser, next) {
this.updated = Date.now();
next();
});
/**
示例5: Number
},
price: {
type: Number,
required: `Price can't be blank.`
},
imageUrl: {
type: String,
required: `Image can't be blank.`
}
})
// Duplicate the ID field.
productSchema.virtual('id').get(function() {
return this._id
})
// Ensure virtual fields are serialised.
productSchema.set('toJSON', {
virtuals: true
})
productSchema.path('name').required(true, `Product name can't be blank.`)
productSchema.path('price').required(true, `Price can't be blank.`)
productSchema.path('price').validate(function(price) {
return Number(price).toString() === price.toString()
}, `Price must be a float number.`)
productSchema.path('imageUrl').required(true, `Image can't be blank.`)
const Product = mongoose.model('Product', productSchema)
export default Product
示例6: function
}, '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
});
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,
示例7: Schema
type: String,
required: 'The type of the build must be provided.',
enum: { values: types, message: 'Invalid type. Valid types are: [ "' + types.join('", "') + '" ].' },
},
is_range: {
type: Boolean,
required: 'You need to provide if the build is a range of versions or one specific version.',
default: false,
},
is_active: { type: Boolean, required: true, default: false },
created_at: { type: Date, required: true },
_created_by: { type: Schema.Types.ObjectId, ref: 'User', required: true },
};
export const buildSchema = new Schema(buildFields, { toObject: { virtuals: true, versionKey: false } });
//-----------------------------------------------------------------------------
// PLUGINS
//-----------------------------------------------------------------------------
buildSchema.plugin(uniqueValidator, { message: 'The {PATH} "{VALUE}" is already taken.' });
//-----------------------------------------------------------------------------
// VALIDATIONS
//-----------------------------------------------------------------------------
buildSchema.path('label').validate((label: any) => {
return validator.isLength(isString(label) ? label.trim() : '', 3);
}, 'Label must contain at least three characters.');
buildSchema.path('built_at').validate((dateString: any) => {
return isDate(dateString) || (isString(dateString) && validator.isISO8601(dateString));
}, 'Date must be a string parsable by Javascript.');
示例8: RegExp
/**
* Must be set to true during authentication.
*/
validated: { type: Boolean },
/**
* User's bookmarks.
*/
bookmarks: []
});
/*
* Validate user's name during his account creation.
*/
userSchema.path('name').validate(function (name) {
return /^\w{5,30}$/g.test(name);
}, 'Invalid name');
/*
* Validate user's email during his account creation.
*/
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
示例9: next
if (this.begin < this.end) {
next();
}
var error = new mongoose.Error.ValidationError(this);
error['date'] = 'The begin\'s date should be before the end\'s date';
next(error);
}
eventSchema.pre('save', checkDate);
/**
* Check that the documents' id are valids.
*/
eventSchema.path('documents').validate((value: Array<any>, respond: (boolean) => void): void => {
async.reduce(value, true, (memo: any, item: any, callback: AsyncSingleResultCallback<any>): void => {
Models.Document.findById(item, (err: any, document: any): void => {
if (err || !document) {
callback(null, false && memo);
}
callback(null, true && memo);
}, 'Invalid ObjectId for the document');
}, (err: string, result: any): any => {
respond(result);
});
});
export var Event = mongoose.model('Event', eventSchema);
示例10: require
ďťż/// <reference path="../definitions/server.d.ts"/>
var mongoose = require('mongoose');
var documentSchema = new mongoose.Schema({
name: { type: String, required: 'Name is required!' },
data: { type: Buffer, required: 'A document can\'t be empty' },
type: { type: String },
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
documentSchema.path('name').validate((name: string, respond: (boolean) => void): void => {
// TODO: check that the document name is unique for the owner.
respond(true);
});
export var Document = mongoose.model('Document', documentSchema);