我有一个简单的 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/