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();});
Have a look at this repo:
https://github.com/jsnomad/koa-restful-boilerplate
It is quite updated and you will get your mind around the koa-mongoose stack... I think it will answer most of your questions; otherwise ask in the comments and will be able to help you :)
For Example How to Create Koa.js+Mongodb
const Koa = require('koa')const mongoose = require('koa-mongoose')const User = require('./models/user')const app = new Koa()app.use(mongoose({ user: '', pass: '', host: '127.0.0.1', port: 27017, database: 'test', mongodbOptions:{ poolSize: 5, native_parser: true }}))app.use(async (ctx, next) => { let user = new User({ account: 'test', password: 'test' }) await user.save() ctx.body = 'OK'})
Example create schemas
const Koa = require('koa')const mongoose = require('koa-mongoose')const app = new Koa()app.use(mongoose({ username: '', password: '', host: '127.0.0.1', port: 27017, database: 'test', schemas: './schemas', mongodbOptions:{ poolSize: 5, native_parser: true }}))app.use(async (ctx, next) => { let User = ctx.model('User') let user = new User({ account: 'test', password: 'test' }) //or let user = ctx.document('User', { account: 'test', password: 'test' }) await user.save() ctx.body = 'OK'})