-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoose_sandbox.js
95 lines (81 loc) · 2.24 KB
/
mongoose_sandbox.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
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/sandbox')
const db = mongoose.connection
db.on('error', (err) => console.error('connection error:', err))
db.once('open', () => {
console.log('db connection successful')
// All database communication goes here
const Schema = mongoose.Schema
const AnimalSchema = new Schema({
type: { type: String, default: 'goldfish' },
size: String,
color: { type: String, default: 'golden' },
mass: { type: Number, default: 0.007 },
name: { type: String, default: 'Angela' },
})
AnimalSchema.pre('save', function(next) {
if (this.mass >= 100) {
this.size = 'big'
} else if (this.mass >= 5 && this.mass < 100) {
this.size = 'medium'
} else {
this.size = 'small'
}
next()
})
AnimalSchema.statics.findSize = function(size, callback) {
return this.find({ size }, callback) // this == Animal
}
AnimalSchema.methods.findSameColor = function(callback) {
return this.model('Animal').find({ color: this.color }, callback) // this == document
}
const Animal = mongoose.model('Animal', AnimalSchema)
const elephant = new Animal({
type: 'elephant',
color: 'gray',
mass: 6000,
name: 'Lawrence',
})
const animal = new Animal({}) // Goldfish
const whale = new Animal({
type: 'whale',
mass: 190500,
name: 'Fig',
})
const animalData = [
{
type: 'mouse',
color: 'gray',
mass: 0.035,
name: 'Marvin',
},
{
type: 'nutria',
color: 'brown',
mass: 6.35,
name: 'Gretchen',
},
{
type: 'wolf',
color: 'gray',
mass: 45,
name: 'Iris',
},
elephant,
animal,
whale,
]
Animal.remove({}, (err) => {
if (err) console.error(err)
Animal.create(animalData, (err, animals) => {
if (err) console.error(err)
Animal.findOne({ type: 'elephant' }, (err, elephant) => {
elephant.findSameColor((err, animals) => {
if (err) console.error(err)
animals.forEach((animal) => console.log(`${animal.name} the ${animal.color} ${animal.type} is a ${animal.size}-sized animal.`))
db.close(() => console.log('db connection closed'))
})
})
})
})
})