【问题标题】:How I can use mongoose and Koa.js我如何使用猫鼬和 Koa.js
【发布时间】:2018-07-05 09:00:21
【问题描述】:

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

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

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?

【问题讨论】:

    标签: javascript mongodb express mongoose koa


    【解决方案1】:

    将你的数据库初始化包装成一个 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();
    });
    

    【讨论】:

    • @aaron 哦,这可能是由于"once" 在监听器连接之前被触发,也许移除它可以完全解决它
    • 现在我们有错误:OverwriteModelError: Cannot overwrite Cat model 一旦编译。
    • 也许你知道,我可以从哪里获得 koa 和 db 的最佳实践?
    • @aaron 我没有同时使用这两种方法,所以我无法确定...但是这个错误可以很容易地修复 :)
    • Jonas W. 我的朋友太棒了!您使用什么堆栈技术?
    【解决方案2】:

    看看这个回购:

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

    它已经相当更新了,你会想到 koa-mongoose 堆栈......我认为它会回答你的大部分问题;否则在 cmets 中询问,将能够帮助您:)

    【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 您的 sn-ps 无法运行。
    • ``` db.open(options.host, database, options.port, options) ^ TypeError: db.open is not a function```
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2021-01-02
    • 2012-10-30
    • 2021-07-29
    • 1970-01-01
    • 2012-02-19
    • 2017-10-11
    • 2015-09-15
    相关资源
    最近更新 更多