REST-API-04-MongoDB

安装

MongoDB
https://www.mongodb.com/
Robomongo (可视化工具)
[https://robomongo.org/]https://robomongo.org/

为了方便,把mogodb 的 bin目录添加到path
1.png

mongod.exe 启动mongodb服务

1
> mongod --port 27019

连接服务器

1
2
3
4
5
6
7
8
9
10
> mongo --port 27019
MongoDB server version: 3.4.7
Server has startup warnings:
2017-08-15T02:29:56.057-0700 I CONTROL [initandlisten]
2017-08-15T02:29:56.058-0700 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-08-15T02:29:56.061-0700 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-08-15T02:29:56.064-0700 I CONTROL [initandlisten]
> show dbs
admin 0.000GB
local 0.000GB

安装为windows系统服务

方法一
用管理员身份运行如下命令,并建好相应的目录

1
> mongod --logpath d:\dev\env\mongo\log --logappend --dbpath d:\dev\env\mongo\db --directoryperdb --serviceName MongoDB --install

1.png

方法二
根据配置文件创建服务

1
> mongod --config <mongo.config> --install

安装 mongoose

Mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具

We can interact with mongoose in 3 different ways:

  1. Callbacks
  2. Promises
  3. Async/Await(Promises)
1
$ npm install mongoose --save

安装 body-parser

1
$ npm install body-parser --save

postman 发送json 数据

4.png

附代码

app.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
const express = require('express');
const logger = require('morgan')
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/APIProject01',{useMongoClient: true});
const app = express();
//Routes
const users = require('./routers/users');
const index = require('./routers/index');
// Middlewares
app.use(logger('dev'));
app.use(bodyParser.json());
//Routes
app.use('/users',users);
app.get('/',index);
//Catch 404 Errors and forword them to error handler
app.use((req,res,next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
//Error handler function
app.use((err,req,res,next) => {
//Response to client
const error = app.get('env') === 'development' ? err : {};
const status = err.status || 500;
//Reponse to ourselves
res.status(status).json({
error:{
message: error.message
}
});
});
//Start the server
const port = app.get('port') || 3000;
app.listen(port,()=> console.log(`Server is listening on port ${port}`));

models/user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName:String,
lastName: String,
email: String,
cars: [{
type: Schema.Types.ObjectId,
ref: 'car'
}]
});
const User = mongoose.model('user',userSchema);
module.exports = User;

controllers/users.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
const User = require('../models/user')
module.exports = {
/*
index:(req,res,next) => {
//Callback 方式
User.find({},(err,users) => {
if(err){
next(err);
}
res.status(200).json(users);
});
},
*/
index: (req,res,next) => {
//Promise 方式
User.find({})
.then(users => {
res.status(200).json(users);
})
.catch(err => {
next(err);
});
},
newUser:(req,res,next) => {
const newUser = new User(req.body);
newUser.save((err,user)=>{
res.status(201).json(user);
//201表示服务局接受并创建成功
});
}
/*
newUser:(req,res,next) => {
const newUser = new User(req.body);
newUser.save()
.then(user => {
res.status(201).json(user);
})
.catch(err => {
next(err);
})
}
*/
}

完整代码

https://github.com/monk8/expressjs-rest-api-server/tree/lesson04

知识来源
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
https://www.bilibili.com/video/av13384870/?from=search&seid=10233919305907705645#page=9
http://blog.csdn.net/qq_16313365/article/details/52313987
http://www.cnblogs.com/zhongweiv/p/mongoose.html
HTTP返回代码 201 304 404 500等代表的含义
http://mongoosejs.com/docs/promises.html