合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
# 浏览器中的schemas > 原文:[Mongoose in the browser](http://mongoosejs.com/docs/browser.html) ## 浏览器中的Mongoose 在3.9.3,Mongoose模式的声明是同构的,那就是,你可以用mongoose的浏览器组件来验证对象在浏览器中对你的mongoose模式。 包括mongoose在你的浏览器代码,你可以使用`require('mongoose')`如果你使用的是[Browserify](https://www.npmjs.com/package/browserify)或可通过script标签引入的mongoose。下面的例子使用mongoose的Amazon的[CloudFront](http://aws.amazon.com/cloudfront/) CDN。 ``` <script type="text/javascript" src="//d1l4stvdmqmdzl.cloudfront.net/4.0.2/mongoose.js"> </script> ``` #### 浏览器中声明模式 When you include the mongoose.js file in a script tag, mongoose will attach a mongoose object to the global window. This object includes a Schema constructor that you can use to define schemas much like in NodeJS. 当你有一个脚本标签的mongoose.js文件,mongoose会附上mongoose对象全局窗口。此对象包含模式的构造函数,您可以使用来定义模式就像在NodeJS。 注:Mongoose的浏览器组件需要一个ECMAScript 5标准的浏览器。特别是,它不会在Internet Explorer 8或Safari 5的工作。 #### 允许你使用mongoose类型 ``` var foodSchema = new mongoose.Schema({name: String}); var breakfastSchema = new mongoose.Schema({ foods: [foodSchema], date: {type: Date, default: Date.now} }); assert.ok(foodSchema.path('name') instanceof mongoose.Schema.Types.String); assert.ok(breakfastSchema.path('foods') instanceof mongoose.Schema.Types.DocumentArray); assert.ok(breakfastSchema.path('date') instanceof mongoose.Schema.Types.Date); ``` ### 在浏览器中验证文档 mongoose的浏览器组件的主要目的是验证对一个给定的模式验证文档。因为mongoose浏览器组件目前不支持任何形式的查询,你负责创建自己的文档。 #### 允许您创建一个模式并使用它来验证文档 ``` var schema = new mongoose.Schema({ name: {type: String, required: true}, quest: {type: String, match: /Holy Grail/i, required: true}, favoriteColor: {type: String, enum: ['Red', 'Blue'], required: true} }); /* `mongoose.Document` is different in the browser than in NodeJS. * the constructor takes an initial state and a schema. You can * then modify the document and call `validate()` to make sure it * passes validation rules. */ var doc = new mongoose.Document({}, schema); doc.validate(function(error) { assert.ok(error); assert.equal('Path `name` is required.', error.errors['name'].message); assert.equal('Path `quest` is required.', error.errors['quest'].message); assert.equal('Path `favoriteColor` is required.', error.errors['favoriteColor'].message); doc.name = 'Sir Lancelot of Camelot'; doc.quest = 'To seek the holy grail'; doc.favoriteColor = 'Blue'; doc.validate(function(error) { assert.ifError(error); doc.name = 'Sir Galahad of Camelot'; doc.quest = 'I seek the grail'; // Invalid, must contain 'holy grail' doc.favoriteColor = 'Yellow'; // Invalid, not 'Red' or 'Blue' doc.validate(function(error) { assert.ok(error); assert.ok(!error.errors['name']); assert.equal('Path `quest` is invalid (I seek the grail).', error.errors['quest'].message); assert.equal('`Yellow` is not a valid enum value for path `favoriteColor`.', error.errors['favoriteColor'].message); done(); }); }); }); ```