Koa2 uses mongodb to write api interface to get data, how to get data elegantly (I am adding data to a new object, it's too low)

const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "youyue";
var obj = {};
module.exports = async(ctx,next)=>{ 

    const num = ctx.query.num,
        page = ctx.query.page,
        sort = ctx.query.sort;

    num = isNaN(num)? 10 : parseFloat(ctx.query.num)
    page = isNaN(page)?0 : parseFloat(ctx.query.page)
    sort = isNaN(sort)?-1 : parseFloat(ctx.query.sort)
       
    console.log(num+"*"+sort+"*"+page);
    MongoClient.connect(url, function (err, client) {
        const db = client.db(dbName);
        const collection = db.collection("site");
        collection.find().sort({ id: sort  }).skip(num*page).limit(num).toArray(function (err, Database){
            console.log(Database);
            //
            obj.result = Database;
        });
    });
    await next(); 
    //
    ctx.body = obj.result;
}

write the query Mongodb paragraph as a function, function return promise. Then call this function and do not low.

function queryToDB(url){
  return new Promise(function(resolve, reject){
    MongoClient.connect(url, function (err, client) {
    const db = client.db(dbName);
    const collection = db.collection('site');
    collection.find().sort({ id: sort  }).skip(num*page).limit(num).toArray(function (err, Database){
        if(err) reject(err);
        else resolve(Database)
    });
});
    

queryToDB(url).then(function(result){
  if(result && result.length > 0){
    ctx.body = result;
  }
}).catch(function(ex){
   // Todo:
});

elegant advice

  1. change MongoClient.connect with util.promisify to promise and use await to wait for the link to succeed.
  2. persist data links and do not link to the database every time you request it.
  3. write const collection = db.collection ('site'); as a class pattern Site.find .
  4. similarly write Site.find as await .
Menu