-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoDBTest.js
76 lines (61 loc) · 1.77 KB
/
mongoDBTest.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
var http = require('http');
var express = require('express');
var app = express();
var credentials = require('./credentials.js');
var mongoose = require('mongoose');
var record = require('./handlers/record.js');
// 模版引擎
var handlebars = require('express3-handlebars').create({
defaultLayout: 'main',
helpers: {
// 段落 可以从视图传递数据到布局{{body}}区以外的地方
section: function (name, options) {
if (!this._sections) {
this._sections = {};
}
this._sections[name] = options.fn(this);
return null;
},
// 资源重定位
static: function (name) {
return require('./lib/static.js').mapping(name);
}
}
});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', process.env.PORT || 3001);
// 连接本地数据库
mongoose.connect('mongodb://localhost/test');
// define a schema
var personSchema = mongoose.Schema({
name: {
first: String,
last: String
}
});
// 关系 数据库db > 数据表collection > 文档 {}
// compile our model 相当于创建了一个数据表
var Person = mongoose.model('Person', personSchema);
// create a document
var axl = new Person({
name: { first: 'xu', last: 'zhongyuan' }
});
// save
axl.save(function (err, item) {
if (err) {
console.log(err)
} else {
console.log(item)
}
});
// 查询person数据表的信息
Person.find(function(err, items){
console.log(items)
})
app.get('/', function (req, res) {
res.render('home')
})
http.createServer(app).listen(app.get('port'), function () {
console.log('Express started in ' + app.get('env') + ' mode on http://localhost:' + app.get('port'));
});