安装
1
mongoose
npm 包

我们安装在 project 下,这样可以让其他app共享使用

1
npm install mongoose

应用模块开发

1 创建配置模块

创建文件 ./home/server/lib/config.js

1
2
3
module.exports = {
    mongodb: 'mongodb://yuu:sdf98786sdf890asdasv766bfa@10.211.55.8:30001/amiami'
};

2 创建mongoose模块

创建文件 ./home/server/lib/db.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var config = require('./config');

// 连接
mongoose.Promise = global.Promise;
var conn = mongoose.createConnection(config.mongodb, {});
conn.on('error',function (error) {
    console.log("数据库错误!");
});
conn.on('connected',function () {
    console.log("数据库连接成功!");
});

// toy数据
var ToySchema = new Schema({
    title:  String,
    adddate: { type: Date, default: Date.now },
    modifydate: { type: Date, default: Date.now }
}, { collection: 'toys' });
exports.ToyDAL = conn.model('toy', ToySchema);

3 添加model函数

创建文件 ./home/server/model/toy.js

1
2
3
4
5
6
var ToyDAL = require('../lib/amiami').ToyDAL;

module.exports.getCount = function(conditions, callback){
	ToyDAL.count(conditions, callback);
};

4 添加action函数

创建文件 ./home/server/action/toy.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var toy = require('../model/toy.js');
var util = require('../lib/util.js');

module.exports.count = function (req, res, next){
    console.log('count');
    toy.getCount(null,function(err, data){
        console.log(data);
        next();
    });
};

module.exports.list = function(req, res){
    console.log('list');
};

5 修改路由配置来支持异步操作

修改文件 ./home/server/action/toy.js

1
2
3
4
5
6
7
8
9
10
    
    ...
    
    router.get('/toy',[
        router.action('toy').count,
        router.action('toy').list
    ]);

    ...

多个方法顺序执行,用[…]的方式。

6 部署app & 运行

1
2
3
4
5
cd ./home
yog2 release --dest debug

cd ./project
yog2 run
  • 测试访问控制器方法 /home/toy

http://127.0.0.1:8085/home/toy

  • 输出
1
2
3
4
count
数据库连接成功!
52635
list

很好!异步的方式按顺序,执行了我们的函数调用。