KOA Respond Error waterline

I'm using waterline ORM to insert a new user data in mongo DB. This is the code from my controller action.

function *(){
    var self = this;
    var attributes= this.request.body
    var userModel = this.models.user;

    userModel.create(attributes).exec(function(err, model){
        self.type = 'application/json';
        self.body = {success:true,description:"user Created"};
    });
}

When I try to execute a request I have the following error:

...../node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;      
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11)

I'm not an expert with Koa but I think that it is because this is an async process and the answer message was written before.

Can anyone help me?? I'm very interested to understand this technology.

I think that it is because this is an async process and the answer message was written before.

Yeah. Koa doesn't know about the query, so it continues on to finalize the response before the query is done executing.

You can yield a function to Koa that wraps the query and notifies it of completion.

function *() {
    // ...

    yield function (done) {
        userModel.create(attributes).exec(function (err, model) {
            self.type = 'application/json';
            self.body = {success:true,description:"user Created"};
            done(err);
        });
    }
}

The use of such thunks is demonstrated further in the documentation of co, which koa is built on, using thunkify to generate such functions.