Mongoose Schema Validations

validations: https://mongoosejs.com/docs/validation.html

instance methods: https://mongoosejs.com/docs/guide.html#methods


 

错误信息一大堆,想看有用的信息?

Mongoose Schema Validations


 

  • Mongoose Schema Validatioins:

定义validation的条件,一旦违反了条件就会出错,require属性,如果没有填该属性,报错;如果添加schema没有预先定义的属性,不会报错,但是会忽略那个新加的属性,不会被保存到数据表中。 

直接运行node product.js

mongo

show dbs

use shopAPP

db.products.find()

Mongoose Schema Validations

product.js

1 const mongoose = require('mongoose');
2 mongoose.connect('mongodb://localhost:27017/shopApp', { useNewUrlParser: true, useUnifiedTopology: true }). //shopApp, use shopApp in mongo!!!
3 .then(() => { 4 console.log("CONNECTION OPEN!!!") 5 }) 6 .catch(err => { 7 console.log("OH NO ERROR!!!!") 8 console.log(err) 9 }) 10 11 const productSchema = new mongoose.Schema({ 12 name: { 13 type: String, 14 required: true, 15 maxlength: 20 16 }, 17 price: { 18 type: Number, 19 required: true, 20 min: [0, 'Price must be positive ya dodo!']. //如果破坏了0这个规则,就会打印“Price must be positive ya dodo!”这个信息 21 }, 22 onSale: { 23 type: Boolean, 24 default: false //如果不另外声明,返回默认值false 25 }, 26 categories: [String], 27 qty: { 28 online: { 29 type: Number, 30 default: 0 31 }, 32 inStore: { 33 type: Number, 34 default: 0 35 } 36 }, 37 size: { 38 type: String, 39 enum: ['S', 'M', 'L'] 40 //size的值只能在S, M, L三个选择中选 41 } 42 43 }); 44 45 //用户自己定义的方法, foundProduct.greet(), 这里调用了greet(),所以this代表foundProduct. 46 productSchema.methods.greet = function () { 47 console.log("HELLLO!!! HI!! HOWDY!!! ") 48 console.log(`- from ${this.name}`) 49 } 50
//instance method 51 productSchema.methods.toggleOnSale = function () { 52 this.onSale = !this.onSale;//充当一个开关的作用,拨动一下是关,再拨动一下是开 53 return this.save();//如果只运行this.save(),it probably takes time, 54 // 怎么解决呢? return this one, and set await when calling foundProduct.toggleOnSale(); 55 } 56 57 // instance method 58 productSchema.methods.addCategory = function (newCat) { 59 this.categories.push(newCat);//更新new category 60 return this.save(); 61 } 62
//static method 63 productSchema.statics.fireSale = function () { //static, 针对于整个Model的方法,而不是某一个实例 64 return this.updateMany({}, { onSale: true, price: 0 }) 65 } 66 67 68 const Product = mongoose.model('Product', productSchema); //products document created!!! 69 70 71 const findProduct = async () => { 72 const foundProduct = await Product.findOne({ name: 'Mountain Bike' }); 73 console.log(foundProduct) 74 foundProduct.greet() 75 await foundProduct.toggleOnSale(); 76 console.log(foundProduct)//这儿为什么又要显示一次?——foundProduct.toggleOnSale();之后save change了,可以看update的效果 77 await foundProduct.addCategory('Outdoors') 78 console.log(foundProduct) 79 } 80 81 Product.fireSale().then(res => console.log(res)) 82 //static methods: fireSale并不是针对与某一个实例对象,而是针对整个model: Product,可以用于批量增删改查 83 //而instance method只是针对于某一个实例对象的操作 84 85 findProduct(); 86 87 88 const bike = new Product({ name: 'Cycling Jersey', price: 28.50, categories: ['Cycling'], size: 'XS' }) 89 bike.save() 90 .then(data => { 91 console.log("IT WORKED!") 92 console.log(data); 93 }) 94 .catch(err => { 95 console.log("OH NO ERROR!") 96 console.log(err) 97 }) 98 99 // runValidators: true必须加上,如果你希望更新的时候也遵循之前的规则!!! 100 Product.findOneAndUpdate({ name: 'Tire Pump' }, { price: 9 }, { new: true, runValidators: true }) 101 .then(data => { 102 console.log("IT WORKED!") 103 console.log(data); 104 }) 105 .catch(err => { 106 console.log("OH NO ERROR!") 107 console.log(err) 108 })

 

上一篇:Mongoose virtual / middleware


下一篇:腾讯云轻量应用服务器部署vue+express+mongoose前后端分离项目