Koa encountered a failure to obtain data while reading mongodb data

  mongodb, question

Problem

InfindAddUsers.jsWhen you find () in, you can read the data normally, but there is no data when you return.

Code

findAddUsers.js

const mongoose = require('mongoose')
 
 let Schema = mongoose.Schema
 
 let UserSchema = new Schema({
 name: String,
 age: Number
 })
 
 let temp = mongoose.model('temp', UserSchema)
 
 exports.findAllUsers = async () => {
 let query = temp.find()
 
 let res = [1,2,3]
 
 await query.exec(function (err, users) {
 if (!  err) {
 res = users
 // console.log(res) // data can be printed here
 }
 })
 // console.log(res) // res here is empty and has no value
 return res
 }

app.js

const Koa = require('koa')
 const app = new Koa()
 
 const router = require('./router/router.js')
 
 const mongoose = require('mongoose')
 mongoose.connect('mongodb://localhost/db1')
 
 app
 .use(router.home.routes())
 .use(router.home.allowedMethods())
 
 app.listen(3000, () => {
 console.log('running')
 })

router.js

const Router = require('koa-router')
 const router = new Router()
 
 const controller = require('../controller/user.js')
 
 module.exports = {
 home: router.get('/', controller.getAllUsers)
 }

user.js

const userHelper = require('../dbhelp/findAllUsers.js')
 
 module.exports = {
 getAllUsers: async (ctx, next) => {
 ctx.body = await userHelper.findAllUsers()
 }
 }
await query.exec(function (err, users) {
 if (!  err) {
 res = users
 // console.log(res) // data can be printed here
 }
 })

You need to write synchronous grammar instead of asynchronous grammar here.