# 瀏覽器中的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();
});
});
});
```