-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongoose.examples.js
More file actions
76 lines (69 loc) · 1.58 KB
/
Copy pathmongoose.examples.js
File metadata and controls
76 lines (69 loc) · 1.58 KB
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
const mongoose = require('mongoose');
const validator = require('validator');
const connectionUrl = "mongodb://127.0.0.1:27017";
const databaseName = "task-manager-api";
const db = mongoose.connect(`${connectionUrl}/${databaseName}`, {
useNewUrlParser: true,
useCreateIndex: true
});
const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
age: {
type: Number,
default: 0,
validate (value) {
if (value < 0) {
throw new Error('Age must be positive number');
}
}
},
email: {
type: String,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('invalid email');
}
}
},
password: {
type: String,
trim: true,
required: true,
minLength: 7,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('password can not contain "password"');
}
}
}
});
const me = new User({name: 'Scott', email: 'jim@beam.com', password: 'asdfasdf'});
me.save().then(() => {
console.log(me);
}).catch((error) => {
console.error(error);
});
// when creating the collection mongoose lower-cases and pluralizes the model name
const Task = mongoose.model('Task', {
description: {
type: String,
required: true,
trim: true
},
completed: {
type: Boolean,
default: false
}
});
const studyMongo = new Task({ description: 'learn mongo', completed: false});
studyMongo.save().then((response)=> {
console.log(response);
}).catch((error) => {
console.error(error);
})