Mongoose--Schema

本文介绍了MongooseJS中Schema的设计方法,包括基本类型、创建模型、实例方法及静态方法等核心概念,并提供了详细的配置选项说明。

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字段

 

转载于:https://my.oschina.net/u/3412211/blog/1617065

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值