Mongoose--Schema

http://mongoosejs.com/docs/guide.html#virtualshtml

每一個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))app

var Blog = mongoose.model('Blog', blogSchema);

Instance methods

經過Schema實例方法methods能夠爲模型(documents)添加實例方法mongoose

// 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)添加實例方法ide

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#autoIndexui

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字段
相關文章
相關標籤/搜索