How I can use mongoose and Koa.js
Asked Answered
Z

3

6

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?

Zest answered 5/7, 2018 at 9:0 Comment(0)
C
5

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();
});
Certie answered 5/7, 2018 at 9:6 Comment(11)
@aaron oh that might be caused by "once" being triggered before the listener is attached, maybe removing it completely solves itCertie
Now we have error: OverwriteModelError: Cannot overwrite Cat model once compiled.Zest
Maybe you know, where I can get the best practices for koa and db?Zest
@aaron I'm not using both, so i cannot really tell ... But that error can be fixed easily :)Certie
Jonas W. It's wonderful my friend! And what stack technology do you use?Zest
@aaron mongodb and express.Certie
Jonas W Herzlichen Dank!Zest
@aaron gehts denn jetzt? Oder hab ichs zum dritten Mal verbockt? :/Certie
Jonas W Es funktioniert jetzt gut!Zest
where is connectDB from?Electrothermal
@Electrothermal thats some wrapper around mongoose.connectCertie
B
1

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

Biogeography answered 5/7, 2018 at 12:58 Comment(4)
Javier Aviles. Danke! And what technology stack do you use?Zest
Well depends a lot... for an easy rest api I have this stack ready to go on github with good docs: github.com/javieraviles/node-typescript-koa-rest But it really depends on your needs and what you like :)Biogeography
This doesn't use koa-mongooseElectrothermal
The one from my answer (not the comment) definitely does :) github.com/jsnomad/koa-restful-boilerplate/blob/master/…Biogeography
V
0

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'
})
Ventriculus answered 27/3, 2019 at 7:43 Comment(2)
Your snippets cant run.Graham
``` db.open(options.host, database, options.port, options) ^ TypeError: db.open is not a function```Electrothermal

© 2022 - 2024 — McMap. All rights reserved.