鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ koa+mongoose顯示不出數(shù)據(jù)

koa+mongoose顯示不出數(shù)據(jù)

在學(xué)習(xí)使用node.js,遇到了些問題。望各位大佬賜教
const koa=require('koa');
const app=new koa();
const route=require('koa-route')
const mongoose=require('mongoose')
const Goods=require('./goods.js')
//連接數(shù)據(jù)庫
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){
**在這里可以打印出數(shù)據(jù)**
    **// 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);

圖片描述

回答
編輯回答
掛念你

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))
2017年8月16日 10:33
編輯回答
維他命
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));

已解決

2017年1月22日 04:54