Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can use mongoose and Koa.js

I have a simple Koa app. I also use mongoose, mongodb(Mlab)

I connected to mongodb. And I can find only ourCat. I see array in console. But I don't know, how I can get and show result on page. And how I can use my request to db in some middleware?

const Koa = require('koa');
const app = new Koa();
const mongoose = require('mongoose');
const mongoUri = '...';

mongoose.Promise = Promise;
function connectDB(url) {
    if (!url) {
        throw Error('Mongo uri is undefined');
    }

    return mongoose
        .connect(url)
        .then((mongodb) => {
            return mongodb;
        });
}
connectDB(mongoUri);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('we\'re connected!');

    const Cat = mongoose.model('Cat', { name: String });
    const kitty = new Cat({ name: 'Zildjian' });
    kitty.save().then(() => console.log('meow'));

    const ourCat = Cat.find({ name: 'Zildjian' });
    ourCat.exec((er, cats) => {
        if (er) {
            console.log(er);
        }
        else if (cats) {

            console.log(cats);
        }
    });
});

app.use(async ctx => {
    ctx.body = 'Hello World';
});

app.listen(3000);

How I can add my answer from db to ctx.response?

like image 955
Aaron Avatar asked Jul 05 '18 09:07

Aaron


2 Answers

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();
});
like image 87
Jonas Wilms Avatar answered Oct 01 '22 08:10

Jonas Wilms


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 :)

like image 30
Javier Aviles Avatar answered Oct 01 '22 10:10

Javier Aviles