###没发现类似co-mongoose的项目,为每一个操作进行thunkify,感觉很麻烦
请问有没有mongoose与koa 结合的示范代码
12 回复
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Promise = mongoose.Promise;
var UserSchema = new Schema({
name: {
type: String,
required: true
}
});
UserSchema.methods.add = function() {
var self = this,
p = new Promise();
self.save(function(error, data) {
if (error) {
p.reject(error);
} else {
p.resolve(null, data);
}
});
return p;
};
mongoose.model('User', UserSchema);
/*
* POST
* create user
*/
var parse = require('co-body'),
mongoose = require('mongoose'),
User = mongoose.model('User');
app.post('/users', function * () {
var body = yield parse(this),
user = new User(body);
yield user.add();
this.body = {
message: 'success',
id: user.id
};
});
就是弄成promise,如果查询,直接exec()就行。
var user = yield User.findById(id).exec();
原先用express或者其他框架的代码不需要改动,只要多封装一层处理逻辑就好。例:
//model.js
var Post = require(‘…/…/db/models/post’);
module.exports = {
fetch: function * () {
var fetch = thunkify(Post.fetch, Post);
var postList = yield fetch();
return postList;
}
}