nodejs渐入佳境[22]-express+mongoDB+mongoose验证

安装 validator

1
> npm install --save validators

user-model

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
var User = mongoose.model('User', {
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: { //验证
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
// {
// email: 'andrew@example.com',
// password: 'adpsofijasdfmpoijwerew',
// tokens: [{
// access: 'auth',
// token: 'poijasdpfoimasdpfjiweproijwer'
// }]
// }

express保存user

1
2
3
4
5
6
7
8
9
10
11
// POST /users
app.post('/users', (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
var user = new User(body);

user.save().then((user) => {
res.send(user);
}).catch((e) => {
res.status(400).send(e);
})
});

完整代码

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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
var mongoose = require('mongoose');
var express = require('express');
var bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
var _ = require('lodash');

const validator = require('validator');


//app
var app = express();
const port = process.env.PORT || 3000;
//express middleware Jonson对象与字符串转换。
app.use(bodyParser.json());

//Promise
mongoose.Promise = global.Promise;
//连接mogodb
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/TodoApp');

//模版
var Todo = mongoose.model('Todo',{
text:{
type:String, //类型
required:true, //必须要有
minlength:1, //最小长度
trim:true //去除空格
},
completed:{
type:Boolean,
default:false //默认值
},
completedAt:{
type:Number,
default:null
}
});


var User = mongoose.model('User', {
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
// {
// email: 'andrew@example.com',
// password: 'adpsofijasdfmpoijwerew',
// tokens: [{
// access: 'auth',
// token: 'poijasdpfoimasdpfjiweproijwer'
// }]
// }





//express route
app.post('/todos',(req,res)=>{
// console.log(req.body);

//建立对象document
var todo = new Todo({
text:req.body.text
});
//保存
todo.save().then((doc)=>{
res.send(doc);
},(e)=>{
res.status(400).send(e);
});

})
//获取所有属性

app.get('/todos', (req, res) => {
Todo.find().then((todos) => {
res.send({todos});
}, (e) => {
res.status(400).send(e);
})
});


//查询id
app.get('/todos/:id', (req, res) => {
var id = req.params.id;

if (!ObjectID.isValid(id)) {
return res.status(404).send();
}

Todo.findById(id).then((todo) => {
if (!todo) {
return res.status(404).send();
}

res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});


//删除
app.delete('/todos/:id', (req, res) => {
var id = req.params.id;

if (!ObjectID.isValid(id)) {
return res.status(404).send();
}

Todo.findByIdAndRemove(id).then((todo) => {
if (!todo) {
return res.status(404).send();
}

res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});

//更新
app.patch('/todos/:id', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['text', 'completed']);

if (!ObjectID.isValid(id)) {
return res.status(404).send();
}

if (_.isBoolean(body.completed) && body.completed) {
body.completedAt = new Date().getTime();
} else {
body.completed = false;
body.completedAt = null;
}

Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
if (!todo) {
return res.status(404).send();
}

res.send({todo});
}).catch((e) => {
res.status(400).send();
})
});


// POST /users
app.post('/users', (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
var user = new User(body);

user.save().then((user) => {
res.send(user);
}).catch((e) => {
res.status(400).send(e);
})
});


//监听
app.listen(port,()=>{
console.log(`Start on port ${port}`);
});
module.exports = {
app,
Todo
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1、打开mongoDB > ./mongod -dbpath /Users/jackson/Downloads/mongodb-data
2、运行 >node postman.js
3、打开postman 选择post 输入 >localhost:3000/users
Body中填入:
{
"email": "zhuimengshaonian@gmail.com",
"password" : "123abc!"
}
返回:
{
"_id": "5bfe54f072e64d6885bf4b2c",
"email": "zhuimengshaonian@gmail.com",
"password": "123abc!",
"tokens": [],
"__v": 0
}