koa+mongoose显示不出数据

在学习使用node.js,遇到了些问题。望各位大佬赐教
const koa=require('koa');
const app=new koa();
const route=require('koa-route')
const mongoose=require('mongoose')
const Goods=require('./goods.js')
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/test')

mongoose.connection.on("connected",function(){
    console.log("mongoDB 连接成功")
})

mongoose.connection.on("error",function(){
        console.log("mongoDB 连接失败")
})

mongoose.connection.on("disconnected",function(){
        console.log("mongoDB 连接断开")
})
const main=function(ctx){
    ctx.response.type='html';
    ctx.response.body='<a href="/">首页</a>'
}

const index=function(ctx){
**在这里可以打印出数据**
    **// ctx.response.type='json';
 //        ctx.response.body={
 //            status:'2',
 //            msg:'Hello World'
 //        }** 
    Goods.find({},function(err,doc){
        在这里就不行
        ctx.response.type='json';
        ctx.response.body={
            status:'2',
            msg:'Hello World'
        }
    if(err){
        ctx.response.type='json';
            ctx.response.body={
            status:'1',
            msg:'Hello World'
        }
    }else{
            ctx.response.type='json';
            ctx.response.body={
                status:'2',
                length:doc.length,
                 msg:doc
             } 
        }
    })
}


app.use(route.get('/',index));
app.use(route.get('/main',main))
app.listen(3000);

图片描述

阅读 2.3k
2 个回答
function runasync(){
    var p=new Promise(function(res,rej){
         Goods.find({},function(err,doc){
             res(doc)
        })
    })

    return p
}
const index=async (ctx,next) =>{
        await runasync().then(
            function(data){
            ctx.response.type='json';
            ctx.response.body={
                staus:200,
                message:data
             }
            }
        );
}


app.use(route.get('/',index));

已解决


Goods.find({},(function(ctx){return function(err,doc){ 
    ctx.response.type='json';
ctx.response.body={
    status:'2',
    msg:'Hello World'
}
if(err){
ctx.response.type='json';
    ctx.response.body={
    status:'1',
    msg:'Hello World'
}
}else{
    ctx.response.type='json';
    ctx.response.body={
        status:'2',
        length:doc.length,
         msg:doc
     } 
}
}
})(ctx))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题