http://mongoosejs.com/docs/guide.html#virtuals
每个Schema映射一个数据库中的集合,限定了文档字段内容
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
允许的Schema类型
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Creating a model
通过Schema创建模型(mongoose.model(modelName, schema))
var Blog = mongoose.model('Blog', blogSchema);
Instance methods
通过Schema实例方法methods可以为模型(documents)添加实例方法
// define a schema
var animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
Statics
通过Schema实例方法statics可以为模型(documents)添加实例方法
animalSchema.statics.findByName = function(name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
};
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function(err, animals) {
console.log(animals);
});
Valid options
http://mongoosejs.com/docs/guide.html#autoIndex
autoIndex
bufferCommands
capped // 集合的封顶大小byte
collection // 设置集合名称
emitIndexErrors //
id // 是否允许通过实体.id查询id
_id // 是否自动创建_id字段
minimize // 是否清除空字段,默认清除
read // 设置schema level
shardKey // 严格模式,传入model的字段不符则不能存入数据库
strict //
toJSON //
toObject //
typeKey //
validateBeforeSave // 保存字段验证
versionKey // 设置versionKey,默认_v,可设为false
collation //
skipVersioning //
timestamps // 设置了timestamps,会加入createdAt and updatedAt字段