Schema

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

Schema是一种以文件形式存储的数据库模型骨架,无法直接通往数据库端,也就是说它不具备对数据库的操作能力,仅仅只是定义数据库模型在程序片段中的一种表现,可以说是数据属性模型(传统意义的表结构),又或着是“集合”的模型骨架。

最简单的理解:

  1. Schema是对文档(表)结构的定义

那如何去定义一个Schema呢,请看示例:

  1. // 定义Schema
  2. UserSchema = new mongoose.Schema({
  3. username: {// 真实姓名
  4. type: String,
  5. required: true
  6. },
  7. password: { // 密码
  8. type: String,
  9. required: true
  10. }
  11. });

基本属性类型有:字符串、日期型、数值型、布尔型(Boolean)、null、数组、内嵌文档等,当然它还有更丰富的对字段进行校验约束的功能。