mongodb 使用问题汇总

69 阅读1分钟
  1. mongoose模型model使用回调中无法配置koa2的ctx?
   const router = require('koa-router')

    // 该方式不妥
    router.get('/login', (ctx, next) => {
       // User为mongoose的model类型
        User.findOne({username: 'jevi'}, (err, result) => {
            ... // some code
            ctx.body = 'something' // 不执行
            ctx.status = 301 // 不执行
            ctx.redirect('http://www.baidu.com') // 不执行
        })
    })
    
    // 该方式妥当
    router.get('/login', async (ctx, next) => {
       // User为mongoose的model类型
        const findUser = await User.findOne({username: 'jevi'})
        if(findUser) {
            ... // some code
            ctx.body = 'something' // 执行
            ctx.status = 301 // 执行
            ctx.redirect('http://www.baidu.com') // 执行
        }
    })