How I can use mongoose and Koa.js
Wrap your database initialization into a Promise:
const Cat = mongoose.model('Cat', { name: String });
function getCats() {
return new Promise((resolve, reject) => {
const ourCat = Cat.find({ name: 'Zildjian' });
ourCat.exec((er, cats) => {
if (er) { reject(er); }
else { resolve(cats); }
});
});
}
So then you can just do:
const connection = connectDB(mongoUri);
app.use(async ctx => {
await connection;
ctx.body = await getCats();
});