nodejs渐入佳境[21]-express+mondoDB应用部署到heroku

express+mongoDB部署到heroku

注意process.env.PORT 与 process.env.MONGODB_URI
源代码postman.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
var mongoose = require('mongoose');
var express = require('express');
var bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');



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

//
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
}
});

//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.listen(port,()=>{
console.log(`Start on port ${port}`);
});
module.exports = {
app,
Todo
}

package.json

package.json配置文件中指定start脚本与node的版本

1
2
3
4
5
6
7
8
"scripts": {
"test": "mocha",
"test-watch":"nodemon --exec 'npm test'",
"start": "node postman.js"
},
"engines":{
"node": "10.13.0"
},

heroku部署

1
2
3
4
5
6
heroku create
heroku addons:create mongolab:sandbox //添加mongodb到 heroku
heroku config //查看
git add .
git commit -m "commit"
git push heroxu master

测试

1
2
访问  domain/todos
配合postman增加document