我如何使用猫鼬和Koa.js

时间:2018-07-05 09:00:22

标签: javascript mongodb express mongoose koa

我有一个简单的Koa应用。 我也用猫鼬mongodb(Mlab)

我已连接到mongodb。 而且我只能找到我们的猫。 我在控制台中看到数组。 但是我不知道如何在页面上显示结果。 以及如何在某些中间件中使用对数据库的请求?

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

如何将我的答案从db添加到ctx.response?

3 个答案:

答案 0 :(得分:3)

将数据库初始化包装到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); }
     });        
  });
}

那么您就可以这样做:

const connection = connectDB(mongoUri);
app.use(async ctx => {
   await connection;
   ctx.body = await getCats();
});

答案 1 :(得分:1)

看看这个仓库:

https://github.com/jsnomad/koa-restful-boilerplate

它已经很新了,您将可以在koa-mongoose堆栈上找到自己的想法...我认为它将回答您的大多数问题;否则,请在评论中提问,将能够为您提供帮助:)

答案 2 :(得分:0)

例如如何创建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'
})

示例创建架构

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'
})