-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09_mongoose.js
105 lines (82 loc) · 2.41 KB
/
09_mongoose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const mongoose = require('mongoose')
mongoose.connect('mongodb+srv://m001-student:m001-mongodb-basics@sandbox.suyhx.mongodb.net/sample_weatherdata', {
useNewUrlParser: true//,useCreateIndex: true
})
const User = mongoose.model('Usersnew', {
name: {
type: String
},
age: {
type: Number
}
})
const me = new User({
name: 'Andrew',
age: 37 //age: 'Mike' will fail validation if we dont give number
})
me.save().then(() => {
console.log(me)
}).catch((error) => {
console.log('Error!', error)
})
//----------------//----------------//----------------//----------------//----------------//----------------
const validator = require('validator')
const User2 = mongoose.model('User2', {
name: {
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: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a postive number')
}
}
}
})
const me2 = new User2({
name: ' Andrew ',
email: 'MYEMAIL@MEAD.IO '
})
me2.save().then(() => {
console.log(me2)
}).catch((error) => {
console.log('Error!', error)
})
const Task = mongoose.model('Task', {
description: {
type: String
},
completed: {
type: Boolean
}
})
const task = new Task({
description: 'Learn the Mongoose library',
completed: false
})
task.save().then(() => {
console.log(task)
}).catch((error) => {
console.log(error)
})
//----------------//----------------//----------------//----------------//----------------//----------------
//----------------//----------------//----------------//----------------//----------------//----------------
//----------------//----------------//----------------//----------------//----------------//----------------
//----------------//----------------//----------------//----------------//----------------//----------------
//----------------//----------------//----------------//----------------//----------------//----------------
//----------------//----------------//----------------//----------------//----------------//----------------