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

https://img2.mukewang.com/5c935c160001663d07280330.jpg

当年话下
浏览 532回答 2
2回答

明月笑刀无情

function runasync(){&nbsp; &nbsp; var p=new Promise(function(res,rej){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Goods.find({},function(err,doc){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;res(doc)&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })&nbsp; &nbsp; return p}const index=async (ctx,next) =>{&nbsp; &nbsp; &nbsp; &nbsp; await runasync().then(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.response.type='json';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.response.body={&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; staus:200,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message:data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; );}app.use(route.get('/',index));已解决

慕桂英546537

Goods.find({},(function(ctx){return function(err,doc){&nbsp;&nbsp; &nbsp; ctx.response.type='json';ctx.response.body={&nbsp; &nbsp; status:'2',&nbsp; &nbsp; msg:'Hello World'}if(err){ctx.response.type='json';&nbsp; &nbsp; ctx.response.body={&nbsp; &nbsp; status:'1',&nbsp; &nbsp; msg:'Hello World'}}else{&nbsp; &nbsp; ctx.response.type='json';&nbsp; &nbsp; ctx.response.body={&nbsp; &nbsp; &nbsp; &nbsp; status:'2',&nbsp; &nbsp; &nbsp; &nbsp; length:doc.length,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;msg:doc&nbsp; &nbsp; &nbsp;}&nbsp;}}})(ctx))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript