javascript - 我如何使用 Mongoose 和 Koa.js

标签 javascript mongodb express mongoose koa

我有一个简单的 Koa 应用程序。 我也用 Mongoose ,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?

最佳答案

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

关于javascript - 我如何使用 Mongoose 和 Koa.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187233/

相关文章:

node.js - 在express中禁用pug(jade)模板的 View 缓存

javascript - 找到 Mongoose 文档,然后按不同层进行随机排序?

javascript - 悬停在不工作时的动画对象

javascript - 使用 jQuery 根据一天中的时间更改 div

mongodb - 当字段不为空时创建部分索引

MongoDB 中的字符串与数字比较效率

javascript - jQuery 中从右侧 trim 空格

javascript - jQuery 验证无法正常工作

c# - Mongodb 数组元素匹配

node.js - 如何处理express.js路由?