Skip to content

基本使用

js
const mongoose = require('mongoose')

// 连接数据库
const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/web')

// 连接成功的回调
conn.on('open', () => {
  console.log('suc')
})

// 1.固定存放的格式(骨架)
const StudentSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    lowercase: true
  },

  age: {
    type: Number,
    min: 5,
    max: 100
  },

  birthday: {
    type: Date,
    dafault: Date.now()
  },

  hobby: {
    type: String,
    validate (v) {
      // 如果不通过验证,会报错。
      return v === 'foo' || v === 'bar'
    }
  }
}, {
  // 添加时间戳信息
  timestamps: {
    createAt: 'createTime',
    updateAt: 'updateTime'
  }
})

// 2.创建模型
// 如果不写 student,Student 会被转为小写并添加上 s。
const Student = conn.model('Student', StudentSchema, 'student')