Search code examples
node.jsmongodbmongoosekoakoa2

Mongoose Koa.js : `await` does not wait untill `exec` of Mongoose is complete.


I'm using latest Koa.js with Mongoose.

I'm using Mongoose's exec to transform the data before it is sent out as response.
I find that whenever I use exec, it does not wait for the exec to complete before sending out the response and that the exec gets completed after the response is sent out.

How can I fix this?

The following is my code.

Route code:

 router.post("/", async ctx=>{
    console.log("data route");
    const datas = await controller.get();
    console.log("AFTER data get", datas);
    ctx.body = datas;
});

Controller code:

exports.get = async ()=>{
    console.log("data get");
    return await dataModel.find().lean().exec(function(err, docs){
        if(err){console.log(err);}
        console.log("inside exec");
        docs = new DataClass(docs);
        console.log(docs);
    });
};

The console log gets printed like so:

data route
data get
AFTER data get undefined
inside exec
[{name:"test1"}, {name:"test2"}]

Solution

  • You are mixing promises (await) with callbacks, which Mongoose doesn't support. Remove your callback and use only promises:

    exports.get = async () => {
        console.log("data get");
    
        const docs = await dataModel.find().lean().exec()
    
        console.log("after exec");
        const dataDocs = new DataClass(docs);
    
        console.log(dataDocs);
        return dataDocs;
    };