nswbmw / koa-mongo

MongoDB middleware for koa, support connection pool.
145 stars 31 forks source link

this.body does not be assigned when mongo returns data #5

Closed guoshencheng closed 9 years ago

guoshencheng commented 9 years ago

I am a fresh man to node.js koa and mongo,When I use then code like demo

app.use(router.get('/', function *(next) {
    this.mongo.db('test').collection('user').findOne({}, function (err, doc) {
        console.log(err, doc);
        this.body = doc;
    });
}));

I can see doc log in console but this.body is empty, I tried assign this.body before use mongodb like

app.use(router.get('/', function *(next) {
    this.body = {"type":"test"};
    this.mongo.db('test').collection('user').findOne({}, function (err, doc) {
        console.log(err, doc);
    });
}));

It returns data, what can I do to make server return data after mongo returns data

nswbmw commented 9 years ago

try:

app.use(router.get('/', function *(next) {
    this.body = yield this.mongo.db('test').collection('user').findOne();
}));
guoshencheng commented 9 years ago

@nswbmw thanks for you answer! My problem has been solved!