1
0

Video 85: Data Validation and Sanitization: Part I

This commit is contained in:
JayWll 2020-02-22 14:28:47 -07:00
parent 72d2114a6c
commit 3bd2ece69b
3 changed files with 45 additions and 19 deletions

View File

@ -183,6 +183,11 @@
"requires": { "requires": {
"memory-pager": "^1.0.2" "memory-pager": "^1.0.2"
} }
},
"validator": {
"version": "10.9.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-10.9.0.tgz",
"integrity": "sha512-hZJcZSWz9poXBlAkjjcsNAdrZ6JbjD3kWlNjq/+vE7RLLS/+8PAj3qVVwrwsOz/WL8jPmZ1hYkRvtlUeZAm4ug=="
} }
} }
} }

View File

@ -11,6 +11,7 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"mongodb": "^3.1.10", "mongodb": "^3.1.10",
"mongoose": "^5.3.16" "mongoose": "^5.3.16",
"validator": "^10.9.0"
} }
} }

View File

@ -1,4 +1,5 @@
const mongoose = require('mongoose') const mongoose = require('mongoose')
const validator = require('validator')
mongoose.connect('mongodb://localhost:27017/task-manager-api', { mongoose.connect('mongodb://localhost:27017/task-manager-api', {
useNewUrlParser: true, useNewUrlParser: true,
@ -7,13 +8,43 @@ mongoose.connect('mongodb://localhost:27017/task-manager-api', {
const User = mongoose.model('User', { const User = mongoose.model('User', {
name: { name: {
type: String type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
}, },
age: { age: {
type: Number type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a positive number')
}
}
} }
}) })
const me = new User({
name: ' Jason ',
email: 'J@SON-WILLIAMS.CA '
})
me.save().then(() => {
console.log(me)
}).catch((error) => {
console.log('Error!', error)
})
const Task = mongoose.model('Task', { const Task = mongoose.model('Task', {
description: { description: {
type: String type: String
@ -23,24 +54,13 @@ const Task = mongoose.model('Task', {
} }
}) })
const task = new Task({ // const task = new Task({
description: 'Learn the Mongoose library', // description: 'Learn the Mongoose library',
completed: false // completed: false
})
task.save().then(() => {
console.log(task);
}).catch((error) => {
console.log('Error!', error)
})
// const me = new User({
// name: 'Jason',
// age: 'Mike'
// }) // })
// //
// me.save().then(() => { // task.save().then(() => {
// console.log(me) // console.log(task);
// }).catch((error) => { // }).catch((error) => {
// console.log('Error!', error) // console.log('Error!', error)
// }) // })