teawithfruit
teawithfruit

Reputation: 767

Callback data out of mongoose query

I want to use koa with mongodb and mongoose with the following code:

var getMessage = function*(params) {
  var messages = MessageModel.find({
    to: params.to
  }, function(err, m) {
    if (err) return console.error(err);
    // How to get the data out of here to work with them?
    console.log(m);
  });

  yield messages.fields;
}

app.get('/message/to/:to', function*(next) {
  this.body =
    yield getMessage(this.params);
});

The function itself works. That means, that the data are printed on the console, but I don't know how to get the data out of the function, to work with them. What's the best way to do this?

Upvotes: 2

Views: 1390

Answers (2)

nikoshr
nikoshr

Reputation: 33344

You would either use the promise returned by .find().exec() without a generator:

var getMessage = function (params) {
  return MessageModel.find({
    to: params.to
  }).exec();  
}

app.get('/message/to/:to', function*(next) {
  this.body = yield getMessage(this.params);
});

or yield the promise inside the generator and return the value you want:

var getMessage = function*(params) {
  var data = yield MessageModel.find({
    to: params.to
  }).exec();

  return data;
}

Have a look at http://blog.stevensanderson.com/2013/12/21/experiments-with-koa-and-javascript-generators/ for more info on what you can yield.

Upvotes: 4

apairet
apairet

Reputation: 3172

disclaimer: I do not know koa.

Have you tried to yield the promise itself? https://github.com/LearnBoost/mongoose/issues/1859

var getMessage = function*(params) {
  var mPromise = MessageModel.find({
    to: params.to
  }).exec();
  yield mPromise;    
}

app.get('/message/to/:to', function*(next) {
  this.body =
    yield getMessage(this.params);
});

Upvotes: 2

Related Questions